vue+webpack+axios跨域请求,No 'Access-Control-Allow-Origin' header'?

用vue-cli搭建的vue项目,axios发起get请求的时候,控制台报错:
Failed to load http://222.16.46.131:8080/Skyworth/changePictureAdmin: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 502.
我要访问的http://222.16.46.131:8080/Skyworth/changePictureAdmin是别人写好的,已经部署在其他服务器的接口,后台有设置cors,请问前端vue项目需要更改什么配置文件,才能成功跨域请求?

阅读 54k
6 个回答

1.你的问题是跨域请求:因为你是在本地开发的,你请求的后台服务器的数据会对非同一个域名下的请求有限制,所以会报错。
2.解决方案:
(1)安装chrome插件 Allow CORS
(2)服务端设置 在php接口脚本中加入以下两句即可:

 header('Access-Control-Allow-Origin:*');//允许所有来源访问
 header('Access-Control-Allow-Method:POST,GET');//允许访问的方式

修改webpack 配置里面的 devServer, 设置proxy,参考 https://webpack.js.org/configuration/dev-server/#devserver-proxy

要进行跨域设置啊

设置请求头

后台那边没设置跨域,你访问不了,可以这样设置

app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', req.headers.origin || '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization,\'Origin\',Accept,X-Requested-With');
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.header('Access-Control-Allow-Credentials', true);
    res.header('X-Powered-By', ' 3.2.1');
    res.header('Content-Type', 'application/json;charset=utf-8');
    if (req.method === 'OPTIONS') {
        res.sendStatus(200);
    } else {
        next();
    }
});
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题