使用多部分表单数据获取帖子 [英] fetch post with multipart form data

查看:157
本文介绍了使用多部分表单数据获取帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在获取这样的网址:

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.

我的代码出了什么问题?

What's wrong with my code?

推荐答案

您正在设置 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):

function sendData(url, data) {
  var formData  = new FormData();

  for(var name in data) {
    formData.append(name, data[name]);
  }

  fetch(url, {
    method: 'POST',
    body: formData
  }).then(function (response) {
     ...
  });
}

这篇关于使用多部分表单数据获取帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆