发布于 3年前

axios发送post请求时出现跨域报错

报错问题

今天在写项目的时候,拿到后端给的的接口,发送请求时却发现报错,但是后端代码中是设置了跨域的:

header("Access-Control-Allow-Origin:*");

看一下报错问题:

Access to XMLHttpRequest at '' from origin '' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

通过报错我们可以看到是请求头不被允许,查阅之后了解到大部分服务器能够识别的请求头为application/x-www-form-urlencoded,而我们axios的post请求的请求头是application/json,所以我们需要对它进行转换。

在页面中引入第三方库qs

安装
npm install qs

在当前页面中引入
import Qs from 'qs'

在axios请求中使用

源代码:

this.$axios
    .post("http://47.94.168.249/php/yingyong.php",
          {
            appName: that.name,
            appType: that.type1
          }
        )
        .then(function(response) {
          console.log(response);
        });

加入Qs库之后:

this.$axios
    .post("http://47.94.168.249/php/yingyong.php",
          Qs.stringify({
            appName: that.name,
            appType: that.type1
          })
        )
        .then(function(response) {
          console.log(response);
        });

然后我们再进行请求就可以拿到数据啦。

©2020 edoou.com   京ICP备16001874号-3