使用 express 框架生成 node 服务器,作为后台服务器,解决跨域请求方式如下:
在 app.js 文件中添加如下代码,即可解决跨域问题
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
//或者
app.all('*', function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Methods', '*');
//设置仅接受 application/json 格式请求
res.header('Content-Type', 'application/json;charset=utf-8');
next();
});