gpt4 book ai didi

javascript - 使用 FormData 进行 fetch()

转载 作者:行者123 更新时间:2023-12-03 03:55:55 25 4
gpt4 key购买 nike

我正在学习使用 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.

你知道为什么在一切正常的情况下它会抛出错误吗?

最佳答案

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

JSON 解析错误几乎肯定是因为您没有在响应中返回 JSON。很难说清楚为什么您会收到弃用警告,但它可能与您的 .then() 调用有关。对于两者,对结果执行一些有用的操作,例如 console.log(res)console.log(error)

关于javascript - 使用 FormData 进行 fetch(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44951413/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com