解决NodeJS+Express模块的跨域访问控制问题
在一个项目上想用NodeJS,在前端的JS(http://localhost/xxx)中ajax访问后端RestAPI(http://localhost:3000/….)时(Chrome)报错
在一个项目上想用NodeJS,在前端的JS(http://localhost/xxx)中ajax访问后端RestAPI(http://localhost:3000/….)时(Chrome)报错:
XMLHttpRequest cannot load http://localhost:3000/auth/xxx/xxx. Origin http://localhost is not allowed by Access-Control-Allow-Origin.
解决代码:
方案一:
var express = require('express'); var app = express(); //设置跨域访问 app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 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(); }); app.get('/auth/:id/:password', function(req, res) { res.send({id:req.params.id, name: req.params.password}); }); app.listen(3000); console.log('Listening on port 3000...');
方案二:
var express = require('express'); var app = express(); app.get('/auth/:id/:password', function(req, res) { res.header("Access-Control-Allow-Origin", "*"); //设置跨域访问 res.send({id:req.params.id, name: req.params.password}); }); app.listen(3000); console.log('Listening on port 3000...');
很赞哦! ( 0
)
相关文章
- 利用 html2canvas 生成文章缩略图
- 纪录片《穹顶之下》全集103分钟1080P高清完整视频
- DoraCMS v2.1.5 版本更新
- DoraCMS v2.1.2 Docker 版本(生产环境)
- Nodejs 内容管理系统 DoraCMS 2.1.4 发布
- DoraCMS 插件化探索(一)
- DoraCMS 2.1.4 关于 '指定用户' 功能的优化说明
- DoraCMS 2.1.4 (发布版非源码) 抢先体验
- angularjs filter 详解
- angularJs的html转义过滤器
- ng-switch on、ng-if/ng-show/ng-hide/ng-disabled标签
- angularjs分页教程