2017-08-15 39 views
0

在Heroku上使用Express/node我得到一個錯誤:在控制檯中重定向了太多次或net :: ERR_TOO_MANY_REDIRECTS。重定向你太多次了 - 在Heroku上的Express/node

我是Express的新手,我嘗試添加重定向,以便將我的兩個自定義域中的所有http請求重定向到https。這是破壞網站的原因。如果有任何想法解決它,那將是驚人的!

var express = require('express'); 
const path = require('path'); 

var app = express(); 

// process.env.PORT gets the port for Heroku or goes to 3000 
const PORT = process.env.PORT || 3000; 

app.enable('trust proxy'); 

// in production on Heroku - re-route everything to https 
if (process.env.NODE_ENV==="production") { 
    app.use((req, res, next) => { 
    if (req.header['x-forwarded-proto'] !== 'https') { 
     res.redirect('https://' + req.hostname + req.url); 
    } else { 
     next() 
    } 
    }) 
} 

app.use(express.static(path.join(__dirname, '/public'))); 

app.get('*', (req, res) => { 
    res.sendFile(path.join(__dirname, 'public/index.html')); 
}); 

app.listen(PORT, function() { 
    console.log('Express server is up on port:' + PORT); 
}); 
+0

FWIW,如果你在使用'app.enable( '信任代理');'然後就可以只需使用'req.protocol'而不是手動檢查''x-forwarded-proto''頭。 'req.protocol'應該在任何一種情況下都有效(有或沒有'信任代理')。 – mscdex

回答

1

改爲使用req.header('x-forwarded-proto')

,並確保,CONSOLE.LOG process.env.NODE_ENVreq.header('x-forwarded-proto')req.hostnamereq.url看到你的重定向工作正常

+0

謝謝ZeroCho - 我現在感覺很愚蠢。這是很好的發現! – Blackstone4