在使用node来做后端时,使用axios获取后台数据时遇到了跨域的问题,报错
Access to XMLHttpRequest at 'http://localhost:8888/Login' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
这里记录一下问题解决的方法。很简单,在app.js中加入下面的代码即可
注意:下面的代码要放在app.use()之前
//设置跨域访问
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.sendStatus(200);
}else{
next();
}
});