nodejs 下解决跨域问题
方法一:(Express框架为例)
//设置跨域访问
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这个模块来解决这个问题(Express框架为例)
npm install cors --save
var cors = require('cors');
app.use(cors({
origin:['http://localhost:8083'],
methods:['GET','POST'],
alloweHeaders:['Conten-Type', 'Authorization']
}));
// 或者
在express项目下面
执行npm install cors
然后在app.js里面
var cors = require('cors');
app.use(cors());
方法三:(Express框架为例)
app.all('*', function(req, res, next) {
console.log(req.method);
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Headers', 'Content-type');
res.header("Access-Control-Allow-Methods", "*");
res.header('Access-Control-Max-Age',1728000);//预请求缓存20天
next();
});
方法四:(koa框架为例)
app.use(async (ctx, next)=> {
ctx.set('Access-Control-Allow-Origin', '*');
ctx.set('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
if (ctx.method == 'OPTIONS') {
ctx.body = 200;
} else {
await next();
}
});
原文链接:
https://blog.csdn.net/weixin_39559301/article/details/89855669
https://www.jianshu.com/p/5dce55bff521
网友评论