CORS 策略已阻止从源“http://192.168.X.X:XX"访问“http://localhost:3000/"处的 XMLHttpRequest [英] Access to XMLHttpRequest at 'http://localhost:3000/' from origin 'http://192.168.X.X:XX' has been blocked by CORS policy
问题描述
尝试从 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 }))
但是得到
访问 XMLHttpRequest 在'http://localhost:3000/' 来自原点'http://192.168.X.X:XX' 已被 CORS 政策阻止:响应预检请求未通过访问控制检查:否'Access-Control-Allow-Origin' 标头存在于请求的资源.
Access to XMLHttpRequest at 'http://localhost:3000/' from origin 'http://192.168.X.X:XX' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
试过这个中间件功能
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();
});
但都是徒劳的.任何可以解决我的问题的帮助或建议???
but all in vain. Any help or suggestion that could resolve my issue???
我实际上犯了一个错误,因为使用 cors()
两次
I was actually making a mistake by using cors()
two times as
this.app.use(cors())
this.app.options('*', cors())
所以当我使用其中之一时,效果很好:)
so when I used one of them, it worked fine :)
推荐答案
尝试添加这两个
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();
});
这篇关于CORS 策略已阻止从源“http://192.168.X.X:XX"访问“http://localhost:3000/"处的 XMLHttpRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!