问题
在前端(http://localhost:8080)异步向后端服务(http://localhost:3000)发出请求,报错:
XMLHttpRequest cannot load http://192.168.102.82:3000. 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.
查找资料,跨域主要问题在header.
header详解:http://kb.cnblogs.com/page/92320/
于是,了解header,对header进行设置,问题迎刃而解了。
解决
1、Access-Control-Allow-Origin 允许的域
2、Access-Control-Allow-Headers 允许的header类型
3、Access-Control-Allow-Methods 允许的header请求类型
代码如下:
//解决跨域问题
app.all('*',function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
if (req.method == 'OPTIONS') {
res.send(200);
}
else {
next();
}
});