在不同的网络中请求nodejs服务的时候,容易被拦截,为了防止这个问题,我们需要在nodejs服务端,设置一下跨域访问,设置跨域有两种方式。
第一种:在express()框架中
//app.js
app.all('*',function (req,res,next) {
res.header("Access-Control-Allow-Origin","*");//允许的域名( * 所有域)
res.header("Access-Control-Allow-Headers","X-Requested-With");//服务器支持的头信息
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");//允许的方法
res.header("X-Powered-By",' 3.2.1')
res.header("Content-Type","application/json;charset=utf-8");
next();
});在进行网络请求的时候,有三种传值方式,其中的一种就是header传值方式,我为了做身份验证,就需要自己在header中放置一些信息。下面是我的设置的跨域方式,仅供参考:
//restAPI跨域访问
app.all('*',"*");
res.header("Access-Control-Allow-Methods",DELETE");
res.header("Content-Type","application/json;charset=utf-8");
res.header("X-Powered-By",' 3.2.1');
res.header('Access-Control-Allow-Headers','X-Requested-With,Content-Type,Authorization,code,name,password,idCard,id,startIndex,pageSize,sorting,startDate,endDate');
next();
})第二种:直接引入cors模块。在koa2框架中
使用方式:
npm install cors;
//app.js
var cors = require('cors');
app.use(cors());我采用的是第一种方式;
详细:
var cors = require('cors');
//设置跨域访问
app.use(cors({
'origin': '*',
'expose': ['WWW-Authenticate','Server-Authorization'],
'maxAge': 5,
'credentials': true,
'methods': ['GET','POST','DELETE'],
'headers': ['Content-Type','Authorization','Accept']
}));相关文章写的都挺不错,记录下来:
HTTP访问控制(CORS)
HTTP消息头(HTTP headers)
从原理分析CORS——我们到底是怎么跨域的