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

报错问题

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

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

看一下报错问题:npm

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.json

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

在页面中引入第三方库qs

安装
npm install qs后端

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

在axios请求中使用服务器

源代码:app

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

加入Qs库以后:post

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

而后咱们再进行请求就能够拿到数据啦。

相关文章
相关标签/搜索