CORS解决跨域
把这个路由配置放在所有路由的前面,方便调用next操作
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");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,PATCH,DELETE,OPTIONS");
// 跨域请求CORS中的预请求
if(req.method=="OPTIONS") {
res.sendStatus(200);/*让options请求快速返回*/
} else{
next();
}
});
module.exports = function cors (req, res, next){
res.header("Access-Control-Allow-Origin", "*");
res.set("Access-Control-Allow-Methods", "POST,PUT,PATCH");
res.set("Access-Control-Allow-Headers", "Content-Type");
// 处理预请求,预请求不需要响应内容,只需要响应200状态码
if(req.method=="OPTIONS") {
res.sendStatus(200);/*让options请求快速返回*/
} else{
next();
}
}
复杂跨域:
- 非GET、HEAD、POST请求。
- POST请求的Content-Type不是application/x-www-form-urlencoded, multipart/form-data, 或text/plain。
- 添加了自定义header,例如Token。