我正在使用Nodejs作为后端。我从路由器功能的外部获取响应对象时遇到问题。在第一个路由功能中,我可以控制台响应对象,但是在第二个路由功能中,我无法将值输入控制台。
我首先声明变量。在第一个路由功能中,我已将响应值发送到变量中,但无法在另一个路由功能中获取值。
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
})
如何将值从一个人的路由功能转换为另一个路由功能。 谢谢。
答案 0 :(得分:4)
要访问变量,请使用变量名称(userNames
)。它不是任何对象的属性,因此请勿使用this
。
通常,您不想这样做。您将获得多个用户的请求之间的竞争状况,并将信息泄漏给错误的人。
改为使用会话。
Express有middleware for this purpose