fetch - multipart/form-data POST 中缺少边界 [英] fetch - Missing boundary in multipart/form-data POST

查看:90
本文介绍了fetch - multipart/form-data POST 中缺少边界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢您的光临.

我想发送一个 new FormData() 作为 POST 请求的 body 使用 获取 api

I want to send a new FormData() as the body of a POST request using the fetch api

操作看起来像这样

var formData = new FormData()
formData.append('myfile', file, 'someFileName.csv')

fetch('https://api.myapp.com', 
  {
    method: 'POST',
    headers: {
      "Content-Type": "multipart/form-data"
    },
    body: formData
  }
)

这里的问题是边界,比如

the problem here is that the boundary, something like

boundary=----WebKitFormBoundaryyEmKNDsBKjB7QEqu

永远不要进入 Content-Type: 标头

应该是这样的

Content-Type:multipart/form-data;边界=----WebKitFormBoundaryyEmKNDsBKjB7QEqu

当你用 new XMLHttpRequest() 尝试相同"操作时,就像这样

when you try the "same" operation with a new XMLHttpRequest(), like so

var request = new XMLHttpRequest()
request.open("POST", "https://api.mything.com")
request.withCredentials = true
request.send(formData)

标题设置正确

Content-Type:multipart/form-data;边界=----WebKitFormBoundaryyEmKNDsBKjB7QEqu

所以我的问题是,

  1. 在这种情况下,如何使 fetch 的行为与 XMLHttpRequest 完全一样?

  1. how do I make fetch behave exactly like XMLHttpRequest in this situation?

如果这不可能,为什么?

if this is not possible, why?

谢谢大家!这个社区或多或少是我取得职业成功的原因.

Thanks everybody! This community is more or less the reason I have professional success.

推荐答案

解决问题的方法是显式设置Content-Typeundefined,这样你的浏览器或者您使用的任何客户端都可以设置它并为您添加该边界值.令人失望但真实.

The solution to the problem is to explicitly set Content-Type to undefined so that your browser or whatever client you're using can set it and add that boundary value in there for you. Disappointing but true.

这篇关于fetch - multipart/form-data POST 中缺少边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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