美文网首页
node 解决跨域问题

node 解决跨域问题

作者: leleo | 来源:发表于2019-11-25 11:29 被阅读0次

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

相关文章

网友评论

      本文标题:node 解决跨域问题

      本文链接:https://www.haomeiwen.com/subject/nvtuectx.html