2017-11-29 15 views
1

私はAngularjsのウェブサイトを持っていて、すべてのHttpトラフィックをHttpsにルーティングしようとしています。そのために、以下のコードを書いていますが、私のウェブサイトを開設するたびにHttpのリダイレクトは起こりません。Nodejs res.redirectが機能しませんか?

var express = require('express'); 
var app = express(); 

app.use(express.static(__dirname + '/public')); // Website part added 
var bodyParser = require('body-parser') 
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: true })) 

app.use(function(req,res,next) { 

    if(req.headers["x-forwarded-proto"] == "http") { 

     res.redirect("https://" + req.headers.host + req.url); 
     return next(); 
    } else { 
     console.log('Request was not HTTP'); 
     return next(); 
    } 
}); 

app.set('views', path.join(__dirname, 'views')); 
app.set('view engine', 'jade'); 

app.get('*', function(req, res) { 
    res.sendFile(__dirname + '/public/index.html'); 
}); 

誰でもこの機能が動作しない理由を教えてください。

編集 - 私は、このミドルウェアはnot getting calledあるmost of the timesその後、いつでも私は私のウェブサイトを開封しておりますことに気づきました。どのようにこれを可能にすることができますか?

編集 - 私は私のindex.htmlに私のセットbase href="/"を持って、それはすべての問題が発生します。

+0

'return next();'を削除します。 –

+0

なぜあなたは 'return next()'が働いていないのかを説明できますか? –

+0

@AikonMogwaiいいえ、まだ動作していません。 –

答えて

0

こんにちは実際に私がしていた間違いは、/publicディレクトリを設定した後にredirectingをミドルウェアに入れていたのですが、正しい方法は/publicディレクトリを設定する前でした。

右のコードは

app.use(function(req,res,next) { 

    if(req.headers["x-forwarded-proto"] == "http") { 

     res.redirect("https://" + req.headers.host + req.url); 
     return next(); 
    } else { 
     console.log('Request was not HTTP'); 
     return next(); 
    } 
}); 
app.use(express.static(__dirname + '/public')); // Website part added 
var bodyParser = require('body-parser') 
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: true })) 

ため、そのHTTPSを強制されませんでしたが、今ではすべてが期待通りに働いています。

0

これはすべての場合にx-forwarded-protoヘッダーに頼ることができないためです。

x-forwarded-protoは、通常、プロキシの後ろにアプリを実行するときに設定され、明らかにあなたのケースではありません。

if (req.protocol === "http") { 
    res.redirect("https://" + req.headers.host + req.url); 
} else { 
    console.log('Request was not HTTP'); 
    return next(); 
} 

それとも、便利エクスプレス要求プロパティreq.secureを使用することができます。

代わりにreq.protocolを使う方が良いでしょう。

+0

req.secureがすべての要求に対してfalseになっています。 –

+0

まだ動作しません。また、いつ私が私のウェブサイトを開いているのか分かりませんが、このミドルウェアは呼び出されていません。 –

+0

'HTTPS'リクエストであっても、req.protocolは' HTTP'リクエストを出力しています。 –

関連する問題