定义一个中间件来添加响应标头,然后在处理app.get(或post等)之前使用
只要将下面的代码;放在处理路由之前就行
设置允许所有域名跨域:
var app = express();
//设置跨域访问
app.all('*', function(req, response, next) {
//设置允许跨域的域名,*代表允许任意域名跨域
response.header("Access-Control-Allow-Origin", "*");
//允许的header类型
response.header("Access-Control-Allow-Headers", "X-Requested-With");
//跨域允许的请求方式
response.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
//设置响应头信息
response.header("X-Powered-By",' 3.2.1')
response.header("Content-Type", "application/json;charset=utf-8");
next();
});
设置允许指定域名“http://www.XXX.com”跨域:
res.header("Access-Control-Allow-Origin","http://www.XXX.com");
设置允许多个域名跨域:
if( req.headers.origin.toLowerCase() == "http://www.xxxx.com" || req.headers.origin.toLowerCase() =="http://127.0.0.1" ) { //设置允许跨域的域名, res.header("Access-Control-Allow-Origin", req.headers.origin); }
如果允许的域名较多,可以将允许跨域的域名放到数组当中:
var orginList=[ "http://www.xxx.com", "http://www.alibaba.com", "http://www.qq.com", "http://www.baidu.com" ]
if(orginList.includes(req.headers.origin.toLowerCase())){ //设置允许跨域的域名,*代表允许任意域名跨域 res.header("Access-Control-Allow-Origin",req.headers.origin); }