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

后端 未结 6 1439
长情又很酷
长情又很酷 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:52

    The trick is pretty simple... The request cycle is still pretty much alive. You can just add a new variable that will create a temporary, calling

    app.get('some/url/endpoint', middleware1, middleware2);
    

    Since you can handle your request in the first middleware

    (req, res, next) => {
        var yourvalue = anyvalue
    }
    

    In middleware 1 you handle your logic and store your value like below:

    req.anyvariable = yourvalue
    

    In middleware 2 you can catch this value from middleware 1 doing the following:

    (req, res, next) => {
        var storedvalue = req.yourvalue
    }
    

提交回复
热议问题