node.js - 从源“http://192.168.XX:XX”访问“http://localhost:3000/”的 XMLHttpRequest 已被 CORS 策略阻止
问题描述
试图Node server (http://localhost:3000)
从Angular 7 (http://192.168.X.X)
设置 CORS 即
this.app.use(cors())
this.app.options('*', cors())
this.app.use(bodyParser.json())
this.app.use(bodyParser.urlencoded({ extended: false }))
但得到
从源“ http://192.168.XX:XX ”访问“ http://localhost:3000/ ”的 XMLHttpRequest已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“访问-请求的资源上存在 Control-Allow-Origin' 标头。
试过这个中间件功能
this.app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Origin', 'http://192.168.X.X:4200');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
但一切都是徒劳的。任何可以解决我的问题的帮助或建议???
**************** 回答 ****************
我实际上是通过使用cors()
两次作为
this.app.use(cors())
this.app.options('*', cors())
所以当我使用其中一个时,它工作得很好:)
解决方案
尝试添加这两个
app.options("/*", function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
res.sendStatus(200);
});
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
next();
});
推荐阅读
- r - 骑士队与勇士队 - 骑士队赢得系列赛的概率包括“0,1,0,0,0,1,1”之类的组合 - 但系列赛在第 5 场比赛后结束
- java - Spring Security hasAuthority 无法正常工作
- database-design - 预订中的客户 X 成员 SQL 数据库
- google-sheets - 谷歌表前6个月数据查询
- node.js - 在 Prisma 中查询时,如何在嵌套关系中使用带有多个查询参数的“AND”运算符?
- stack - 检测到 Pwnable bof Stack 粉碎
- reactjs - 如何为对象定义正确的数据类型
- java - WSDoAllReceiver:安全处理失败
- arduino - 如何使用黑色药丸板读取和输出 pwm?
- java - 使用 Jgit 使用 Mockito 编写单元测试