express+node.js搭建的服务器和在sublimeServer下的页面请求报跨域错误

1.前端页面使用vue中的axios请求nodejs响应。报以下错误:

Failed to load http://localhost:3000/users/validate: 
Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:8080' is therefore not allowed access.

前端页面请求代码

后端请求成功响应代码:

2.解决跨域问题

在express下的app.js文件,在路由配置钱加上以下代码(允许跨域),注意加的位置。

app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    next();
});

3.重启后台服务器,可以返回响应消息

原文地址:https://www.cnblogs.com/wgl0126/p/10578750.html