我使用 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
})
如何将值从一个路由函数获取到另一个路由函数。 谢谢。
最佳答案
要访问变量,请使用变量名称(userNames
)。它不是任何对象的属性,因此不要使用 this
。
一般来说,您不想这样做。您将在多个用户的请求之间遇到竞争条件,并将信息泄露给错误的人。
改用 session 。
express 有middleware for this purpose
关于javascript - 如何从路由函数外部获取Nodejs响应对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57733126/