在 Express.js 中使用 next() 将变量传递给下一个中间件 [英] Passing variables to the next middleware using next() in Express.js

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

问题描述

我想将一些变量从第一个中间件传递给另一个中间件,我尝试这样做,但是req.somevariable 被指定为未定义".>


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

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