2016-06-01 26 views
1

我想讀取並傳遞req.params到另一箇中間件。但是我得到一個空的對象作爲迴應。req.params沒有通過中間件

var app = require('express')(); 
app.get('/foo/:bar', function(req,res, next) { 
    console.log('1 --', req.params); 
    next(); 
}); 
app.use(function(req, res, next) { 
    console.log('2 --', req.params); 
    res.end(); 
}) 
app.listen(3000); 

我打這個網址 -

http://localhost:3000/foo/hello

輸出我得到的是 -

1 -- { bar: 'hello' } 
2 -- undefined 

如何req.params傳遞到另一箇中間件?

回答

0

AFAIK,req.params僅在明確設置參數的處理程序中可用。

所以此工程:

app.get('/foo/:bar', function(req,res, next) { 
    console.log('1 --', req.params); 
    next(); 
}); 

app.use('/foo/:bar', function(req, res, next) { 
    console.log('2 --', req.params); 
    res.end(); 
}); 

如果你不希望出現這種情況,你需要不斷的PARAMS參考在不同的屬性:

app.get('/foo/:bar', function(req,res, next) { 
    console.log('1 --', req.params); 
    req.requestParams = req.params; 
    next(); 
}); 

app.use(function(req, res, next) { 
    console.log('2 --', req.requestParams); 
    res.end(); 
}); 
0
//route 
app.get('/foo/:bar', yourMiddleware, function(req, res) { 
    res.send('params: ' + req.params); 
}); 

//middleware 
function yourMiddleware(req, res, next) { 
    console.log('params in middleware ' + req.params); 
    next(); 
} 
+1

這個的人更好的選項,除此之外,還可以使用'''res.locals._params''來設置一個請求 - 響應週期。 – Nivesh

+1

有人可以告訴我爲什麼這是downvoted? – Thalaivar

+0

嗨Thalaivar,謝謝你的迴應。但是,您的解決方案僅適用於特定路線。我想把req.params傳遞給我的中間件所有的路由。 –