How do I POST with multipart form data using fetch?(如何使用 fetch 发布多部分表单数据?)
问题描述
我正在获取这样的 URL:
I am fetching a URL like this:
fetch(url, {
mode: 'no-cors',
method: method || null,
headers: {
'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
'Content-Type': 'multipart/form-data'
},
body: JSON.stringify(data) || null,
}).then(function(response) {
console.log(response.status)
console.log("response");
console.log(response)
})
我的 API 期望数据是 multipart/form-data 所以我正在使用这种类型的 content-type... 但它给了我一个响应状态码为 400.
My API expects the data to be of multipart/form-data so I am using content-type of this type... But it is giving me a response with status code 400.
我的代码有什么问题?
推荐答案
您将 Content-Type 设置为 multipart/form-data,然后使用JSON.stringify 在正文数据上,返回 application/json.您的内容类型不匹配.
You're setting the Content-Type to be multipart/form-data, but then using JSON.stringify on the body data, which returns application/json. You have a content type mismatch.
您需要将数据编码为 multipart/form-data 而不是 json.通常上传文件时使用multipart/form-data,比application/x-www-form-urlencoded(HTML表单默认).
You will need to encode your data as multipart/form-data instead of json. Usually multipart/form-data is used when uploading files, and is a bit more complicated than application/x-www-form-urlencoded (which is the default for HTML forms).
multipart/form-data 的规范可以在 RFC 中找到1867.
有关如何通过 javascript 提交此类数据的指南,请参阅 这里.
For a guide on how to submit that kind of data via javascript, see here.
基本思想是使用 FormData 对象(在 IE < 10) 中不支持:
The basic idea is to use the FormData object (not supported in IE < 10):
async function sendData(url, data) {
const formData = new FormData();
for(const name in data) {
formData.append(name, data[name]);
}
const response = await fetch(url, {
method: 'POST',
body: formData
});
// ...
}
根据这篇文章确保不是 设置 Content-Type 标头.浏览器会为你设置好,包括boundary参数.
Per this article make sure not to set the Content-Type header. The browser will set it for you, including the boundary parameter.
这篇关于如何使用 fetch 发布多部分表单数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 fetch 发布多部分表单数据?
基础教程推荐
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
