CORS(Cross-origin resource sharing),跨域资源共享,是一份浏览器技术的规范,用来避开浏览器的同源策略
简单来说就是解决跨域问题的除了jsonp外的另一种方法
使用express写的接口,只能在内部使用,如果想要外部的服务访问,就涉及到了跨域。但是又不想用jsonp,其实有一个node模块,可以轻松实现跨域
npm install cors --save
然后在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相应路径添加如下:
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