首页 > 解决方案 > 从源“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())

所以当我使用其中一个时,它工作得很好:)

标签: node.jsangularcorsangular7

解决方案


尝试添加这两个

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();
});

推荐阅读