关于javascript:在Internet Explorer 11中通过fetch-api发布FormData-object时为空值

Empty values when posting FormData-object via fetch-api in Internet Explorer 11

我已经编写了一个React组件,该组件应该用于我的应用程序中的所有形式。 单击某个按钮后,我将进行一些验证,最后我要将表单发布到服务器。
这是当前部分的外观:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 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));

所示的代码片段在Chrome中工作正常。 但是,在IE11中不是。
另一方面,取消注释Content-Type标头时,它也会在Chrome中中断。

如https://stackoverflow.com/a/46642899/615288所示,它始终为"multipart/form-data"。 但是,即使将其设置为multipart/form-data,这些值也不会发送到服务器。

我正在使用来自https://github.com/jimmywarting/FormData以及whatwg-fetch的FormData polyfill。

我不知道这里发生了什么,因为FormData从版本9开始就可以在IE中工作。

旁注:当注释掉整个标题部分时,它仍然可以在Chrome中使用,因为浏览器似乎猜测出了正确的标题(在开发人员工具中可以看到)


我遇到了这个问题,但是在无奈中,我发现向FormData对象添加一个额外的字段突然使所有字段都出现在服务器上。

1
2
3
4
5
6
const formData = new FormData(theForm);

// this somehow makes it work
formData.append('fakefield', 'nothing to see here!');

fetch(theForm.action).then(/* do the stuff */);

我不知道为什么会这样,但是在我添加该行之前,服务器收到了{}作为请求正文,之后又收到了{ myformfield: 'myvalue', myotherfield: 'myothervalue', fakefield: 'nothing to see here!' }

希望这可以节省一些挫败感:)


今天有人在回购报告中向我报告了这一点。

https://github.com/jimmywarting/FormData/issues/44

显然" IE无法在主体为类型Blob的XHR上设置Content-Type头",这就是为什么您得到错误的content-type头的原因。 将版本更新为可能3.0.7可以解决此问题