感谢您的光临.
我想发送一个 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
所以我的问题是,
在这种情况下,如何使 fetch 的行为与 XMLHttpRequest 完全一样?
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-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 中缺少边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
即使在调用 abort (jQuery) 之后,浏览器也会等待Browser waits for ajax call to complete even after abort has been called (jQuery)(即使在调用 abort (jQuery) 之后,浏览器也会等待 ajax 调用
JavaScript innerHTML 不适用于 IE?JavaScript innerHTML is not working for IE?(JavaScript innerHTML 不适用于 IE?)
XMLHttpRequest 无法加载,请求的资源上不存在“AXMLHttpRequest cannot load, No #39;Access-Control-Allow-Origin#39; header is present on the requested resource(XMLHttpRequest 无法加载,请求的资
XHR HEAD 请求是否有可能不遵循重定向 (301 302)Is it possible for XHR HEAD requests to not follow redirects (301 302)(XHR HEAD 请求是否有可能不遵循重定向 (301 302))
NETWORK_ERROR:XMLHttpRequest 异常 101NETWORK_ERROR: XMLHttpRequest Exception 101(NETWORK_ERROR:XMLHttpRequest 异常 101)
XMLHttpRequest 206 部分内容XMLHttpRequest 206 Partial Content(XMLHttpRequest 206 部分内容)