使用Express.js中的next()将变量传递给下一个中间件 [英] Passing variables to the next middleware using next() in Express.js
本文介绍了使用Express.js中的next()将变量传递给下一个中间件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好吧,我的问题是我想将一些变量从第一个中间件传递到另一个中间件,我尝试这样做,但是有 req.somevariable
是一个给定为'undefined'。
Well, my question is I want to pass some variable from the 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;
...
推荐答案
将变量附加到 req
对象,而不是 res
。
Attach your variable to the req
object, not res
.
而不是
res.somevariable = variable1;
有:
req.somevariable = variable1;
正如其他人所指出的那样, res.locals
是通过中间件传递数据的推荐方法。
As others have pointed out, res.locals
is the recommended way of passing data through middleware.
这篇关于使用Express.js中的next()将变量传递给下一个中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文