将变量传递给下一个使用express()的中间件 [英] passing variables to the next middleware using next() in expressjs

查看:366
本文介绍了将变量传递给下一个使用express()的中间件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是,我想把一些变量从第一个中间件传递给另一个中间件,我尝试这样做,但是req.somevariable是一个给定的'undefined'。






  // 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆