AXIOS Post无法与Internet Explorer中的REACT应用程序一起使用

时间:2019-02-22 20:58:35

标签: reactjs post axios internet-explorer-11

注意:我已经有一个解决方案,我想在此作为问题/答案提供,因此如果其他人遇到此问题,他们可以查看对我有用的内容是否也可以为他们。

我要做什么: 我一直在研究需要将数据发送到Java Servlet的REACT应用程序。 在线查看时,我看到建议使用AXIOS来执行Post命令来做到这一点。

问题: 我有以下代码在Edge,Chrome和Firefox中正常运行,但在Internet Explorer中失败(错误是在Internet Explorer的浏览器控制台中找不到 URLSearchParams

        let axiosConfig = {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        };            
        // Putting together the data to be passed to the java servlet.
        const params = new URLSearchParams();
        params.append('var1', this.state.data1);
        params.append('var2', this.state.data2);

        var urlToPost = 'https://localhost:8080/someServlet/someMethod';

        axios.post(urlToPost, params, axiosConfig)
            .then((res) => {
                // Handling Response from Servlet.
                console.log("AXIOS POST RESPONSE RECEIVED: ", res);
            })
            .catch((err) => {
                // Handler exception error thrown by Servlet.
                alert('Error during submission');
            })            

2 个答案:

答案 0 :(得分:0)

我在网上看到了一些有关如何解决它的建议,并且在IE中有些“可行”,这意味着我在IE浏览器控制台上没有任何错误,但是当数据到达Java Servlet时,提取的数据字段为空。

因此,对我而言,解决方案是使用IE浏览器时使用jQuery进行发布,例如:

       // This if statement checks to see if the user's browser is Internet Explorer
       // if its true then use jQuery to do the POST
       if((navigator.userAgent.indexOf("MSIE") !== -1 ) || (!!document.documentMode === true )) //IF IE > 10
       {
           var myObject = {
              var1: this.state.data1,
              var2: this.state.data2
            };
            var urlToPost = 'https://localhost:8080/someServlet/someMethod';
            $.post(urlToPost, myObject, 
                function(result) {  
                   // handle response
               })
              .done(function(result) {
                   // handle response
              })
              .fail(function(result) {
                  // handle response
              })
              .always(function(result) {
                 // handle response
              });

       } else {
        // use the AXIOS POST command code from my initial question above
       }

在此之前,我必须使用以下命令安装jquery并答应:

  

npm安装jquery

     

npm安装es6-promise

然后在我的react文件的顶部,我必须包括以下导入:

import $ from 'jquery';
import { polyfill } from 'es6-promise'; polyfill();

有了这些更改,Internet Explorer不再给我任何控制台错误,并且我拥有的Java Servlet能够从HTTP响应对象中提取非空数据。

答案 1 :(得分:0)

您将需要在IE中为URLSearchParams使用polyfill

https://www.npmjs.com/package/url-search-params-polyfill