2016-12-21 3 views
0

私がしたいこと。nodejs(express)のrouter.route()にミドルウェアを設定する

router.post('/xxxx', authorize , xxxx); 

    function authorize(req, res, next) 
    { 
    if(xxx) 
     res.send(500); 
    else 
    next(); 
    } 

各ルートでセッションを確認したいと思います。 しかし、ルータはこのように書かれています。

router.route('/xxx/xxxx').post(function(req, res) { 
    // blah lah here... 
    // 
}); 

だから私はセッションをチェックするミドルウェアをセットアップし、私は一つのことをやっての代わりに、すべてのrequest.Anyにチェック物事はもう少し汎用的にしたかったし、単一のauthorize機能を持っていると思ったことができますか提案。

答えて

2

ルートを定義する前にミドルウェア機能を定義すると、すべてのルートで有効なセッションがないかどうかを確認できます。これを行う方法の例については、以下のコードを参照してください。

いくつかのルートは、彼らはあなたがあなたのmiddlware機能あなたのコメントを1として

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

//This is the middleware function which will be called before any routes get hit which are defined after this point, i.e. in your index.js 
app.use(function (req, res, next) { 

    var authorised = false; 
    //Here you would check for the user being authenticated 

    //Unsure how you're actually checking this, so some psuedo code below 
    if (authorised) { 
    //Stop the user progressing any further 
    return res.status(403).send("Unauthorised!"); 
    } 
    else { 
    //Carry on with the request chain 
    next(); 
    } 
}); 

//Define/include your controllers 

を「」を使用する前に、これらを定義する有効なセッションを持っているユーザーを必要としない、つまり、あなたは2つの選択肢があり、公開されている場合このミドルウェアが一部のルートにのみ影響を与えることについては、以下の2つの例を参照してください。

オプション1 - ミドルウェアの前に特定のルートを宣言します。

app.post("/auth/signup", function (req, res, next) { ... }); 
app.post("/auth/forgotpassword", function (req, res, next) { ... }); 

//Any routes defined above this point will not have the middleware executed before they are hit. 

app.use(function (req, res, next) { 
    //Check for session (See the middlware function above) 
    next(); 
}); 

//Any routes defined after this point will have the middlware executed before they get hit 

//The middlware function will get hit before this is executed 
app.get("/someauthorisedrouter", function (req, res, next) { ... }); 

オプション2はどこかmiddlware関数を定義し、

/middleware.js

module.exports = function (req, res, next) { 
    //Do your session checking... 
    next(); 
}; 

を必要な場所あなたがそれを好きな場所今あなたがそれを必要とすることができ、それを必要としています。あなたがこの機能を実現することができる方法の一般的なアイデアを提供します

/index.js

var session_check = require("./middleware"), 
    router = require("express").Router(); 

//No need to include the middlware on this function 
router.post("/signup", function (req, res, next) {...}); 

//The session middleware will be invoked before the route logic is executed.. 
router.get("/someprivatecontent", session_check, function (req, res, next) { ... }); 


module.exports = router; 

希望。

+0

これは解決しますが、すべてのルートに適用されますが、正確には私が望んでいないと思うので、サインアップやパスワードを忘れるなどの特定のルートに追加したいです。 –

+0

あなたはそこに2つの選択肢があります本当に。ミドルウェアを宣言する前に、サインアップを定義してパスワード経路を忘れるか、ミドルウェア機能を使用するすべての経路にミドルウェア機能を渡すことができます。 –

+0

ありがとうございました –

関連する問題