问题
I have written a React-component which should be used for all forms in my application. When a certain button is clicked I make some validation and finally I want to post the form to the server. This is what this part currently looks like:
// get what should be submitted
const formData = new FormData(theForm)); // theForm is the DOM-element
// post the form-data element
fetch(theForm.action,
{
credentials: "include", //pass cookies, for authentication
method: theForm.method,
headers: {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
//"Content-Type": "application/x-www-form-urlencoded"
},
body: formData
})
.then(res => console.dir(res))
.catch(reason => console.error(reason));
The shown snippet work fine in Chrome
. However, in IE11
it is not.
On the other hand, when uncommenting the Content-Type
header, it will also break in Chrome
.
As found https://stackoverflow.com/a/46642899/615288 it is always "multipart/form-data"
. But even if I set it to multipart/form-data
the values are not send to the server.
I am using the FormData polyfill from https://github.com/jimmywarting/FormData as well as whatwg-fetch
.
I don't see what is going on here as FormData should work in IE since version 9.
Sidenote: When commenting out the whole header-part it still works in Chrome
as the browser seems to guess the correct ones (as it can be seen in the developer-tools)
回答1:
Somebody reported this to me today in the repo.
https://github.com/jimmywarting/FormData/issues/44
Apparently "IE fail to set Content-Type header on XHR whose body is a typed Blob" that's why you get wrong content-type header. updating the version to might 3.0.7 fix this
回答2:
I had this problem, but after much frustration I found out that appending an extra field to the FormData
object suddenly all the fields appeared on the server.
const formData = new FormData(theForm);
// this somehow makes it work
formData.append('fakefield', 'nothing to see here!');
fetch(theForm.action).then(/* do the stuff */);
I don't know why it works, but before I added that line the server received {}
as the request body and afterwards it received { myformfield: 'myvalue', myotherfield: 'myothervalue', fakefield: 'nothing to see here!' }
Hope this can save someone a bit of frustation :)
来源:https://stackoverflow.com/questions/47593227/empty-values-when-posting-formdata-object-via-fetch-api-in-internet-explorer-11