如何使用 fetch 发布多部分表单数据?

2022-01-20 00:00:00 fetch javascript fetch-api

我正在获取这样的 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.

相关文章