Monir Tuhin
Monir Tuhin

Reputation: 117

How to get Nodejs response object from the outside of the routing function?

I am using Nodejs as a back-end. I am facing a problem with getting a response object from the outside of the router function. In first routing function i can do to console the response object but in second routing function i can not able to get the values in to console.

I declare the variable in first. In first routing function i have send the response values in to variable but can't able to get the values in another routing function.

let userNames;

router.get('/getUsers', function (req, res) {
    const users = [
    {name: 'Mark'},
    {name: 'Rafallo'},
    {name: 'Samir'},
    ]
    this.userNames = users; // will be response json
    console.log('userValues', this.userNames); // able to get the json in to console
    res.send(users);
})

router.get('/demoUser', function (req, res) {
    console.log('userValues', this.userNames); // unable to get the json in to console
})

How to get values from one's routing function in to another routing function. Thanks.

Upvotes: 0

Views: 213

Answers (1)

Quentin
Quentin

Reputation: 944544

To access a variable use the variable name (userNames). It isn't a property of any object, so don't use this.

Generally, you don't want to do this though. You'll get race conditions between requests from multiple users and leak information to the wrong people.

Use a session instead.

Express has middleware for this purpose

Upvotes: 4

Related Questions