Passing variables to the next middleware using next() in Express.js

后端 未结 6 1434
长情又很酷
长情又很酷 2020-11-27 10:11

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

6条回答
  •  眼角桃花
    2020-11-27 10:45

    I don't think that best practice will be passing a variable like req.YOUR_VAR. You might want to consider req.YOUR_APP_NAME.YOUR_VAR or req.mw_params.YOUR_VAR.

    It will help you avoid overwriting other attributes.

    Update May 31, 2020

    res.locals is what you're looking for, the object is scoped to the request.

    An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any). Otherwise, this property is identical to app.locals.

    This property is useful for exposing request-level information such as the request path name, authenticated user, user settings, and so on.

提交回复
热议问题