125

我正在获取这样的 URL:

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 的响应。

我的代码有什么问题?

4

2 回答 2

240

您将 设置Content-Typemultipart/form-data,然后JSON.stringify在返回的主体数据上使用application/json. 您的内容类型不匹配。

您需要将数据编码为multipart/form-data而不是json. 通常在上传文件时使用,比(HTML 表单的默认设置)multipart/form-data稍微复杂一些。application/x-www-form-urlencoded

的规范multipart/form-data可以在RFC 1867中找到。

有关如何通过 javascript 提交此类数据的指南,请参见此处

基本思想是使用FormData对象(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参数。

于 2016-02-04T16:15:22.177 回答
34

我最近在使用 IPFS 并解决了这个问题。IPFS 上传文件的 curl 示例如下所示:

curl -i -H "Content-Type: multipart/form-data; boundary=CUSTOM" -d $'--CUSTOM\r\nContent-Type: multipart/octet-stream\r\nContent-Disposition: file; filename="test"\r\n\r\nHello World!\n--CUSTOM--' "http://localhost:5001/api/v0/add"

基本思想是每个部分(由boundarywith中的字符串分割--)都有自己的标题(Content-Type例如,在第二部分中)。FormData对象为您管理所有这些,因此这是实现我们目标的更好方法。

这转化为 fetch API,如下所示:

const formData = new FormData()
formData.append('blob', new Blob(['Hello World!\n']), 'test')

fetch('http://localhost:5001/api/v0/add', {
  method: 'POST',
  body: formData
})
.then(r => r.json())
.then(data => {
  console.log(data)
})
于 2016-11-21T06:41:15.477 回答