带有http和https和CORS问题的Express服务器设置 [英] Express server setup with http and https and CORS issue
问题描述
我在express server.js中有这样的配置:
I have such configuration in express server.js :
app.use(function (request, response, next) {
response.header('Access-Control-Allow-Origin', '*');
response.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
response.header(
'Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, X-Api-Key'
);
next();
})
app.options('*', function (request, response) {
response.send(200);
});
app.listen(httpPort, function () {
console.log('Listening on port: ' + httpPort);
});
httpsServer = https.createServer(credentials, app);
httpsServer.listen(httpsPort, function () {
console.log('Listening on port: ' + httpsPort);
});
我还必须指出:
https:// local:8000 和 http:// local:8001
此刻,我正尝试从 http:// local: 8001 到 https:// local:8001 / api ,但出现CORS问题:
At moment I'm trying to do call from http://local:8001 to https://local:8001/api but getting CORS issue :
跨域请求已阻止:同一来源策略不允许读取 https: // local:8000 / api / 。可以通过将资源移到同一域或启用CORS来解决此问题。
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://local:8000/api/. This can be fixed by moving the resource to the same domain or enabling CORS.
在Chrome上,我得到:
On Chrome I'm getting :
XMLHttpRequest无法加载 https:// local:8000 / 。所请求的资源上没有 Access-Control-Allow-Origin标头。因此,不允许访问来源' http:// local:8001 。
XMLHttpRequest cannot load https://local:8000/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://local:8001' is therefore not allowed access.
如何对快递服务器上的CORS进行排序
How to sort problem with CORS on express server
推荐答案
这对我的问题进行了排序:
This sorted my issue:
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://local:8001');
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, X-Api-Key'
);
res.header('Access-Control-Allow-Credentials', 'true');
if ('OPTIONS' === req.method) {
res.sendStatus(200);
}
else {
next();
}
});
这篇关于带有http和https和CORS问题的Express服务器设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!