Node跨域cors模块,nodejs+express跨域

Node跨域cors模块 NodeJS+Express跨域

 

什么是CORS

CORS(Cross-origin resource sharing),跨域资源共享,是一份浏览器技术的规范,用来避开浏览器的同源策略

简单来说就是解决跨域问题的除了jsonp外的另一种方法

 

安装cors模块

使用express写的接口,只能在内部使用,如果想要外部的服务访问,就涉及到了跨域。但是又不想用jsonp,其实有一个node模块,可以轻松实现跨域

npm install cors --save

 

使用cors模块

然后在app.js文件中

//引入跨域模块
var cors = require('cors'); 

//注册跨域模块
app.use(cors()); 

注意:这个代码一定要,写在注册路由的前面。此模块也可以,当做路由中间件,指定某一个,或者某一部分路由,拥有跨域功能。

 

其他代码参考

Try passing control to the next matching route. If Express is matching app.get route first, then it won't continue onto the options route unless you do this (note use of next):

app.get('somethingelse', function(req, res, next) {
    //..set headers etc.

    next();
});

In terms of organising the CORS stuff, I put it in a middleware which is working well for me:

//CORS middleware
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', 'example.com');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');

    next();
}

//...
app.configure(function() {
    app.use(express.bodyParser());
    app.use(express.cookieParser());
    app.use(express.session({ secret: 'cool beans' }));
    app.use(express.methodOverride());
    app.use(allowCrossDomain);
    app.use(app.router);
    app.use(express.static(__dirname + '/public'));
});

 

Nginx跨域配置

然而添加了这些之后,仍然不好使。查了查,可能是要在nginx上也作设置,在nginx相应路径添加如下:

location ^~ /test {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Methods' 'OPTION, POST, GET';
    add_header 'Access-Control-Allow-Headers' 'X-Requested-With, Content-Type';
}

之后重新加载nginx配置即可,大功告成。
 

参考资料:https://stackoverflow.com/questions/7067966/why-doesnt-adding-cors-headers-to-an-options-route-allow-browsers-to-access-my 

参考资料:https://blog.csdn.net/qq_28505809/article/details/97270429

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值