2

次のように定義されたサーバーがあります。

app.get('/', function(req, res) {
  // gets something
}

app.post('/', function(req, res) {
  // updates something, need to be authenticated
}

ここpostで、認証されたユーザーに対してのみアクションを実行したいので、次のようにauthそれらの間にミドルウェアを追加します。

app.get('/', function(req, res) {
  // gets something
}

app.use('/', function(req, res) {
  // check for authentication
}

app.post('/', function(req, res) {
  // updates something, need to be authenticated
}

このようにGETしてPOST、ユーザーを認証する必要があります。

app.use問題は、Express がミドルウェアに入らないことです。すべてのルートapp.useの前にミドルウェアを配置すると、機能します。app.VERB

私が望むようにする方法はありますか?

4

2 に答える 2

2

このタイプのチェックを再利用可能なメソッドに入れて、ルート ハンドラに渡すのが好きです。

function ensureAuth(req, res, next){
  if(req.user) next(); // Auth check
  else res.redirect('/');
}

app.post('/', ensureAuth, function(req,res){
  // User is authenticated
}
于 2013-10-27T01:26:02.163 に答える