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.

相关文章