使用axios时,解决provisional headers are shown问题

在使用vue+axios的post发送请求时,在响应的回调函数中获取不到响应的数据,代码如下所示

        var vm = new Vue({
            el: '#app',
            data: {
                obj: ''
            },
            methods: {
                postData: function() {
                    var url = 'http://xxxxxxxxxx' 
                    axios.post(url, {
                        id: '0',
                        name: 'idNmae'
                    }).then(function(response) {
                        console.log(response);
                    }).catch(function(error) {
                        console.log(error);
                    })
                }
            }
        });

打开chrom中的NetWork选项看到请求头信息中出现一个警告 Provisional headers are shown
这时候以为后端的给的接口除了问题,为了验证一下,改使用了vue-resource中的post方法请求了这个接口,发现能够获取响应的数据,这时候问题肯定不是接口问题了,问题还是在axios的post请求上,根据 Provisional headers are shown 这个警告分析一下应该是请求头出现的问题,回想在之前用Ajax的post的请求的时候都要设置请求头的,那么就在axios中使用post也设置一下请求头看可不可以,更改后的代码如下

     var vm = new Vue({
            el: '#app',
            data: {
                obj: ''
            },
            methods: {
                postData: function() {
                    var url = 'http://xxxxxxxxxx' 
                     axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';  //此处是增加的代码,设置请求头的类型
                    axios.post(url, {
                        id: '0',
                        name: 'idNmae'
                    }).then(function(response) {
                        console.log(response);
                    }).catch(function(error) {
                        console.log(error);
                    })
                }
            }
        });

设置了axios.defaults.headers['Content-Type'] 之后就能够请求到响应的信息了。大功告成!

猜你喜欢

转载自blog.csdn.net/it_cgq/article/details/78749037