XMLHttpRequest cannot load http://localhost:3000/. No 'Access-Control-Allow-Origin' header is presen

express解决
跨域问题主要在header上下功夫
首先提供一个w3c的header定义 http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
再提供一个网友提供的header详解 http://kb.cnblogs.com/page/92320/

这两个有助于帮助大家理解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(); } });

参考:解决NodeJS+Express模块的跨域访问控制问题:Access-Control-Allow-Origin - 推酷
最后介绍一个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'); });
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值