您现在的位置:首页 >> 前端 >> 内容

express如何解决跨域问题?

时间:2017/12/19 10:07:17 点击:

  核心提示:express解决跨域问题主要在header上下功夫遗憾的是跨域相关的两个header属性我都没有找到相关的定义,下面直接告诉大家1是Access-Control-Allow-Origin 允许的域2...

express解决跨域问题主要在header上下功夫

遗憾的是跨域相关的两个header属性我都没有找到相关的定义,

下面直接告诉大家

1是Access-Control-Allow-Origin 允许的域

2是Access-Control-Allow-Headers 允许的header类型

第一项可以直接设为* 表示任意

但是第二项不能这样写,在chrome中测试跨域发现报错,

最终的代码看起来是这个样子:

app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With"); res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); res.header("X-Powered-By",' 3.2.1') if(req.method=="OPTIONS") res.send(200);/*让options请求快速返回*/ else next(); });

代码完善:

//allow custom header and CORS app.all('*',function (req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild'); res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS'); if (req.method == 'OPTIONS') { res.send(200); /让options请求快速返回/ } else { next(); } });

最后介绍一个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'); });

Tags:EX XP PR RE 
作者:网络 来源:ken_ding的博