設(shè)置允許所有域名跨域:
app.all("*",function(req,res,next){
//設(shè)置允許跨域的域名,*代表允許任意域名跨域
res.header("Access-Control-Allow-Origin","*");
//允許的header類型
res.header("Access-Control-Allow-Headers","content-type");
//跨域允許的請(qǐng)求方式
res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
if (req.method.toLowerCase() == 'options')
res.send(200); //讓options嘗試請(qǐng)求快速結(jié)束
else
next();
}
app.all("*",function(req,res,next){
//設(shè)置允許跨域的域名繁疤,*代表允許任意域名跨域
res.header("Access-Control-Allow-Origin","http://www.zhangpeiyue.com");
//允許的header類型
res.header("Access-Control-Allow-Headers","content-type");
//跨域允許的請(qǐng)求方式
res.header("Access-Control-Allow-Methods","DELETE,PUT,POST,GET,OPTIONS");
if (req.method.toLowerCase() == 'options')
res.send(200); //讓options嘗試請(qǐng)求快速結(jié)束
else
next();
}
設(shè)置允許多個(gè)域名跨域:
app.all("*",function(req,res,next){
if( req.headers.origin.toLowerCase() == "http://www.zhangpeiyue.com"
|| req.headers.origin.toLowerCase() =="http://127.0.0.1" ) {
//設(shè)置允許跨域的域名疑故,*代表允許任意域名跨域
res.header("Access-Control-Allow-Origin", req.headers.origin);
}
//允許的header類型
res.header("Access-Control-Allow-Headers", "content-type");
//跨域允許的請(qǐng)求方式
res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
if (req.method.toLowerCase() == 'options')
res.send(200); //讓options嘗試請(qǐng)求快速結(jié)束
else
next();
}
如果允許的域名較多诗赌,可以將允許跨域的域名放到數(shù)組當(dāng)中:
app.all("*",function(req,res,next){
var orginList=[
"http://www.zhangpeiyue.com",
"http://www.alibaba.com",
"http://www.qq.com",
"http://www.baidu.com"
]
if(orginList.includes(req.headers.origin.toLowerCase())){
//設(shè)置允許跨域的域名鲁僚,*代表允許任意域名跨域
res.header("Access-Control-Allow-Origin",req.headers.origin);
}
//允許的header類型
res.header("Access-Control-Allow-Headers", "content-type");
//跨域允許的請(qǐng)求方式
res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
if (req.method.toLowerCase() == 'options')
res.send(200); //讓options嘗試請(qǐng)求快速結(jié)束
else
next();
}