問題描述
感謝您的光臨.
我想發送一個 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 likeXMLHttpRequest
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模板網!