app.all("*", function (req, res, next) {
// 防止undefined 报错
if (!req.headers.origin) {
return
}
//设置允许跨域的域名,*代表允许任意域名跨域,如果前端显示不能使用‘*’,则用`request`里的域名代替
//凡是在header中设置过的参数,必须在Access-Control-Allow-Headers 添加一遍
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header( 'Access-Control-Allow-Credentials','true');
res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
res.header('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8')
res.header('Access-Control-Allow-Headers',
'Origin, X-Requested-With,' +
' Content-Type,Accept,' +
'Access-Control-Allow-Origin,' +
'Access-Control-Allow-Credentials,' +
'Access-Control-Allow-Methods,' +
'Access-Control-Allow-Headers')
if (req.method.toLowerCase() === 'options') {
res.sendStatus(200); //让options预验证尝试请求快速结束
} else {
next();
}
})
网友评论