fetch() 与 FormData

真相

我正在学习使用 Node.js 和 multer 上传文件。我已经配置了主要的 app.js 文件,以及 upload.html。

我的表格:

<form id="uploadForm" action="/uploads" enctype="multipart/form-data" method="post">
    <input id="upload-input" type="file" name="uploads" multiple>
    <button class="upload-button" type="button">File</button>
</form>

和 script.js,我试图用它来处理表单数据并使用 fetch() 发布它:

uploadInput.addEventListener('change', function() {
    let files = event.target.files;

    if(files.length > 0) {
        let formData = new FormData();

        for(let i = 0; i < files.length; i++) {
            let file = files[i];

            formData.append('uploads', file);
        }

        fetch('uploads', {
            method: 'POST',
            body: formData
        })
        .then(res => res.json(), error => error.message);
    }
});

文件正在上传,除了两个错误外,一切都很好。首先在浏览器控制台显示:

uploader:1 Uncaught (in promise) SyntaxError: Unexpected token s in JSON at position 0

WebStorm IDE 控制台中的第二个:

(node:51729) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated.

你知道为什么它会抛出错误,而一切正常吗?

乔恩·B

看起来问题出在 .then(res => res.json(), error => error.message);

JSON 解析错误几乎可以肯定是因为您没有在响应中返回 JSON。很难说为什么您会收到弃用警告,但这可能与您的.then()电话有关。对于两者,对结果做一些有用的事情,例如console.log(res)console.log(error)

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章