私はエクスプレスを使って簡単なウェブサイトを開発しています。ページをレンダリングする前にnodejsチェックセッションを作成する方法について混乱しているため、ユーザーがログインしなかった場合、ユーザーは何も表示されません。
Railsでは非常に簡単だと思います。アプリケーションコントローラーにコードを追加するだけです。しかし、nodejsでそのようなことをどのように処理するのですか?
ルートの前に認証をチェックするミドルウェア関数を定義してから、各ルートでそれを呼び出します。たとえば、app.jsで
// Define authentication middleware BEFORE your routes
var authenticate = function (req, res, next) {
// your validation code goes here.
var isAuthenticated = true;
if (isAuthenticated) {
next();
}
else {
// redirect user to authentication page or throw error or whatever
}
}
次に、これを呼び出して、ルートでこのメソッドを渡します(認証パラメーターに注意してください)。
app.get('/someUrl', authenticate, function(req, res, next) {
// Your normal request code goes here
});
app.get('/anotherUrl', authenticate, function(req, res, next) {
// Your normal request code goes here
});