2017-04-24 32 views
3

我有運行在80和443端口的應用程序。當用戶點擊http版本應用程序時,它應該被重定向到HTTPS。我已經嘗試了下面的代碼來做到這一點。HTTP到HTTPS重定向在節點和角2應用

function handleRedirects(req, res, next) { 
    if (!req.secure) { 
     return res.redirect('https://' + req.get('host') + req.url); 
    } 
    next(); 
} 

app.use(handleRedirects); 

https.createServer(credentials, app).listen(443, function() { 
    console.log('App is running on port 443'); 
}); 

// all other routes are handled by Angular 
app.get('/*', function(req, res) { 
    console.log("Default handler\n\n\n\n") 
    res.sendFile(path.join(__dirname, '/../../dist/index.html')); 
}); 

app.listen(80, function() { 
    logger.info('App is running on port 80'); 
    admins.refresh(); 
}); 

所以,當應用程序開始,如果我打本地主機應該重定向到https://localhost。但它沒有按預期工作。 代碼有什麼問題。我已經接受了HTTPS redirection for all routes node.js/express - Security concerns

回答

1

下面的代碼解決了我的問題。

var app = express(); 
app.get('/refresh', function (req, res) { 
    res.send(200); 
}); 
https.createServer(credentials, app).listen(443, function() { 
    console.log('App is running on port 443'); 
}); 


var http = express(); 

http.get('/', function (req, res) { 
    res.redirect('https://' + req.get('host') + req.url); 
}) 
http.listen(80, function() { 
    logger.info('App is running on port 80'); 
}); 
1

我只是設置了https,以便它只在生產環境中重定向,我在我的網站上使用的代碼如下所示。

module.exports.httpsRedirect = function(req,res,next){ 
if(req.headers['x-forwarded-proto'] != 'https' && process.env.NODE_ENV === 'production') 
    res.redirect('https://'+req.hostname+req.url) 
else 
    next() /* Continue to other routes if we're not redirecting */ 
};