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

问题描述

感谢您的停留。

我想发送新的FormData()作为<$ c使用

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

永远不会进入内容类型: hea der

never makes it into the Content-Type: header

它看起来应该是这样的

Content-Type:multipart / form-数据; boundary = ---- WebKitFormBoundaryyEmKNDsBKjB7QEqu

使用新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 /形式数据; boundary = ---- WebKitFormBoundaryyEmKNDsBKjB7QEqu

所以我的问题是,


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

如果这不可能,为什么?

if this is not possible, why?

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

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

推荐答案

问题的解决方案是明确设置 Content-Type undefined 以便您的浏览器或您正在使用的任何客户端都可以设置它并在那里添加该边界值您。令人失望但却是真实的。

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中缺少边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 22:57