简体   繁体   English

如何从路由功能外部获取Nodejs响应对象?

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

I am using Nodejs as a back-end. 我正在使用Nodejs作为后端。 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. 谢谢。

To access a variable use the variable name ( userNames ). 要访问变量,请使用变量名( userNames )。 It isn't a property of any object, so don't use this . 它不是任何对象的属性,所以不要使用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 Express 为此提供了中间件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM