node.js解决跨域方案

服务端

1、通过使用cors模块解决跨域问题

var express = require('express')
  , cors = require('cors')
  , app = express();
 
app.use(cors());
 
app.get('/products/:id', function(req, res, next){
  res.json({msg: 'This is CORS-enabled for all origins!'});
});
 
app.listen(80, function(){
  console.log('CORS-enabled web server listening on port 80');
});  

2、NodeJS+Express解决跨域问题:Access-Control-Allow-Origin

// 允许跨域访问
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();
});

 

客户端

反向代理 或者jsonp 

推荐阅读 跨越解决大全

  

posted @ 2020-12-31 15:19  菜鸟小何  阅读(2074)  评论(0编辑  收藏  举报