//设置跨域访问
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();
});
另外cors()模块也可以实现
如果在发生post等等其他请求,出现控制台报错Request header field Content-Type is not allowed by Access-Control-Allow-Header。需要添加请求头的信息时:
app.all('*', function (req, res, next) {
//响应头指定了该响应的资源是否被允许与给定的origin共享。*表示所有域都可以访问,同时可以将*改为指定的url,表示只有指定的url可以访问到资源
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", " Origin, X-Requested-With, Content-Type, Accept");
//允许请求资源的方式
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();
});