Sunday, February 11, 2018

javascript - fetch - Missing boundary in multipart/form-data POST



thanks for stopping by.



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




the operation looks something like this





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



never makes it into the Content-Type: header



it should look like this



Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryyEmKNDsBKjB7QEqu




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)






the headers are correctly set



Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryyEmKNDsBKjB7QEqu



so my question is,





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


  2. if this is not possible, why?




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


Answer



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.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...