我有以下代码:
var https = require('https');
var http = require('http');
var express = require('express');
var app = express();
var router = express.Router();
app.use('/', router);
//have 'server' listen for https
var server = https.createServer(config.sslCredential, app);
server.listen(config.serverPort);
//listen server on http, and always redirect to https
var httpServer = http.createServer(function(req,res){
res.redirect(config.serverDomain+req.url);
});
httpServer.listen(config.httpServerPort);
但是我无论如何都无法将https请求重定向到https请求,使用node.js和express 4.x应该如何正确处理呢?
req.secure
指令无法使用。请参考此处的答案:https://dev59.com/U1wY5IYBdhLWcg3wJU94 - Will Hitchcockreq.host
(在express 3.x中使用)现在变成了req.hostname
(在express 4.x中使用)。 - Claudiu Hojdafunction ensureSecure(req, res, next){ if(req.headers['x-forwarded-proto'] === 'https'){ // 这是安全的,继续执行 return next() }; res.redirect('https://' + req.headers.host) }
- Phil Andrews