将变量传递给下一个使用express()的中间件 [英] passing variables to the next middleware using next() in expressjs
本文介绍了将变量传递给下一个使用express()的中间件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
// app.js
..
app.get('/ someurl /',middleware1,中间件2)
...
//// middleware1
...
某些条件
...
res.somevariable = variable1;
next();
...
//// middleware2
...
某些条件
...
variable = req.somevariable;
...
感谢您的回答
解决方案
将您的变量附加到 req
对象,而不是 res
。
而不是
res.somevariable = variable1;
有:
code> req.somevariable = variable1;
编辑:
正如其他人所指出的那样,
res.locals
是通过中间件传递数据的推荐方式。 Well my question is I want to pass some variable from first middleware to another middleware and I tried doing this but there was req.somevariable is a given as 'undefined'.
//app.js
..
app.get('/someurl/',middleware1,middleware2)
...
////middleware1
...
some conditions
...
res.somevariable = variable1;
next();
...
////middleware2
...
some conditions
...
variable = req.somevariable;
...
Thanks for answering.
解决方案
Attach your variable to the req
object, not res
.
Instead of
res.somevariable = variable1;
Have:
req.somevariable = variable1;
Edit:
As others have pointed out, res.locals
is the recommended way of passing data through middlewares.
这篇关于将变量传递给下一个使用express()的中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文