记录 - 跨域遇到的坑
以下是记录【node】跨域的配置,
1. Cors中间件
const app = express();
app.use(cors())
这个就不用细说了吧
2. 自己配置通行
app.all('*',function(req,res,next){
res.header("Access-Control-Allow-Origin",req.headers.origin || '*');
res.header("Access-Control-Allow-Methods","PUT,GET,POST,DELETE,OPTIONS");
res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , User-Account, User-TOken,');
if(req.method == 'OPTIONS'){
res.sendStatus(200);
}
else{
next();
}
});
*号代表全部,换成自己域名,ip啥都行
重点说说
如果客户端发送的请求中有自定义header的属性,则会把请求变为复杂请求。
会先发送一个OPTIONS类型的请求去服务端尝试建立链接,重点的重点一定要将前端发来的自定义请求头部加入到header中,否则会一直报跨域
例:请求
axios({
...option,
// 添加自定义请求头
headers : {
'User-TOken' : '123456',
'User-Account' : 'accountSky'
}
})
后端
app.all('*',function(req,res,next){
res.header("Access-Control-Allow-Origin",req.headers.origin || '*');
res.header("Access-Control-Allow-Methods","PUT,GET,POST,DELETE,OPTIONS");
res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , User-Account, User-TOken,');
if(req.method == 'OPTIONS'){
res.sendStatus(200);
}
else{
next();
}
});
必须在‘Access-Control-Allow-Headers’处添加自己自定义的请求头。
翻了很多文章都没说提到这点,
希望这篇文章能帮你节省时间~~