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

Posted

技术标签:

【中文标题】在 Internet Explorer 11 中通过 fetch-api 发布 FormData-object 时为空值【英文标题】:Empty values when posting FormData-object via fetch-api in Internet Explorer 11 【发布时间】:2018-05-15 13:11:06 【问题描述】:

我编写了一个 React 组件,它应该用于我的应用程序中的所有表单。单击某个按钮时,我会进行一些验证,最后我想将表单发布到服务器。 这就是这部分目前的样子:

// 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));

显示的 sn-p 在Chrome 中工作正常。但是,在IE11 中却不是。 另一方面,当取消注释Content-Type 标头时,它也会中断Chrome

发现 https://***.com/a/46642899/615288 时始终为 "multipart/form-data"。但即使我将其设置为multipart/form-data,这些值也不会发送到服务器。

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

我看不到这里发生了什么,因为 FormData 从版本 9 开始应该可以在 IE 中工作。

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

【问题讨论】:

【参考方案1】:

今天有人在 repo 中向我报告了这件事。

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

显然“IE 无法在其正文是类型化 Blob 的 XHR 上设置 Content-Type 标头”,这就是您得到错误内容类型标头的原因。将版本更新到可能 3.0.7 可以解决此问题

【讨论】:

【参考方案2】:

我遇到了这个问题,但经过一番挫折后,我发现在 FormData 对象上附加一个额外的字段突然所有字段都出现在服务器上。

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!'

希望这可以为某人节省一点挫败感:)

【讨论】:

您在“theForm”中传递的内容,我面临同样的问题。

以上是关于在 Internet Explorer 11 中通过 fetch-api 发布 FormData-object 时为空值的主要内容,如果未能解决你的问题,请参考以下文章