零基础解决node.js+express服务跨域问题,No ‘Access-Control-Allow-Origin’ header is present on the requested resou
前端-vue跨域
这里说明一下,网上很多都是潦草的说什么方法,具体根本自己就不会解决,
写那么多博客一模一样有什么意思,又不能解决问题,看到我就想小嘴抹蜜。
- 出现的问题:
Access to XMLHttpRequest at 'http://localhost:3000/user/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();
}
});