javascript - 如何从路由函数外部获取Nodejs响应对象?

标签 javascript node.js express

我使用 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/

相关文章:

node.js - Mongoose Actor 错误

node.js - node.js 是如何工作的?

node.js - 在 NodeJS 中存储服务器端 cookie 的位置?

javascript - PayPal Checkout 客户端 : Can users change the order amount in JavaScript?

javascript - 合并两个编译步骤的源映射

javascript - 在 jQuery Mobile 中作为链接的选项值

node.js - 用于用户注册的 Sails.js 闪现消息

javascript - Google 涂鸦如何制作动画

javascript - 如何实现 WebRTC 录制到 Node.js 服务器

javascript - Node.Js 的简单用户身份验证