2013-01-14 41 views
0

下面的代码演示了如何从中间件登录req.hash_id。它显示为undefined。无论如何,我可以得到这个工作?或者经常使用中间件来解析“:hash”。将.param的req变量传递给.use?

app.param("hash",function(req, res, next, id){ 
    req.hash_id = id; 
    return next(); 
}); 

app.use(function(req, res, next){ 
    console.log(req.hash_id); 
    return next(); 
}); 

回答

2

我不认为你可以使用req.params中间件的功能里面,因为它绑定到特定的路线。尽管您可以使用req.query,但您必须以不同的方式编写路线,例如/user?hash=12345abc。不确定将app.param的值传递给app.use

如果你有一个特定结构的路线,像/user/:hash你可以简单地写

// that part is fine 
app.param('hash',function(req, res, next, id){ 
    req.hash_id = id; 
    return next(); 
}); 

app.all('/user/:hash', function(req, res, next) { // app.all instead app.use 
    console.log(req.hash_id); 
    next(); // continue to sending an answer or some html 
}); 

// GET /user/steve -> steve 
+0

我想用'app.use()'中间件拦截所有的'app.param之间的呼叫() '和'app.all()'并使用'req.hash_id'变量。但这里是'undefined'完整的示例:https://gist.github.com/4532510。 – ThomasReggi

+0

这有点棘手。 'app.param'是路由器的一部分。 'req.hash_id'是'undefined',因为中间件在'router'之前被调用。将'app.use'放在''router'后面将不起作用,因为路由器是中间件链的末端。 – zemirco

+0

是的,我想我现在知道它是如何工作的。我摆脱了'app.param',并解析'app.use'中间件中的'req.url'作为散列。 – ThomasReggi