我目前正在将流量重定向到我的 Node 服务器上的 https:
var express = require('express');
var path = require('path');
var app = express();
var port = process.env.PORT || 8080;
app.set('port', port);
app.use(express.static(path.join(__dirname, './src/public')));
app.all('*', function(req, res, next) {
if(req.headers["x-forwarded-proto"] === "https"){
// OK, continue
return next();
};
res.redirect('https://'+req.hostname+req.url);
})
app.get('*', function( req, res ) {
res.sendFile(path.join(__dirname, './src/public/index.html'));
} );
app.use(require('./server/routes/index'));
app.listen(process.env.PORT || 8080, function (){
console.log('Express started on port ' + app.get('port') + '; press Ctrl-C to terminate.');
});
module.exports = app;
这样做时,我的 AJAX 调用无法通过:net::ERR_CONNECTION_REFUSED
。当然,当我删除上述重定向时,我的 AJAX 调用就会通过。
我设法从遇到此问题的人那里找到了另一篇关于 SO 的帖子,但建议是设置 Access-Control-Allow-Origin 来接受任何传入的 AJAX 请求,这似乎是一个安全问题。
如果我想继续使用 https 重定向,有没有办法允许 AJAX 调用通过,或者我需要关闭重定向吗?
最佳答案
使用req.protocal和req.get('host')获取协议(protocol)和主机url
app.all('*', function(req, res, next) {
if(req.headers["x-forwarded-proto"] === "https"){
// OK, continue
return next();
};
res.redirect(req.protocol + '://' + req.get('host') + req.originalUrl);
})
关于向我的 Node 服务器发送 AJAX 请求 - 未通过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41413440/