【问题标题】:Return variable from NodeJS ExpressJS从 NodeJS ExpressJS 返回变量
【发布时间】:2021-09-25 16:43:51
【问题描述】:

Wazzup 编码员,

我正在使用 Express 和 Ajax 将数据从客户端发送到 NodeJS。我不明白为什么我的变量没有在函数之外定义。谁能告诉我哪里可能出错了?

//send javascript to client
    res.send(`
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        var size = {
          clientwidth: window.innerWidth,
          clientheight: window.innerHeight
        };
        var objectData = JSON.stringify(size);
        $.post('/size', { clientwh: objectData });
    </script>
    `);

//retrieve javascript from client
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({extended: true}));
    app.post('/size', (req, res) =>
    {
        var clientwidth = req.body.clientwh.match(/\d+/);
        var clientheight = req.body.clientwh.match(/(\d+)(?!.*\d)/gm);
        const clientResolution = [clientwidth, clientheight];
        res.json({ok: true});
        console.log(clientResolution)
    });
    
    console.log(clientResolution) //ReferenceError: clientResolution is not defined

感谢您的帮助:)

【问题讨论】:

    标签: jquery node.js ajax express


    【解决方案1】:

    这里有多个问题。

    变量范围

    首先,clientResolution 被定义为 app.post() 回调函数内部的一个局部变量,因此它的作用域是该函数并且仅在该回调函数内部可用。

    查看我在您的代码中插入的 cmets:

    app.post('/size', (req, res) =>
    {
        var clientwidth = req.body.clientwh.match(/\d+/);
        var clientheight = req.body.clientwh.match(/(\d+)(?!.*\d)/gm);
        const clientResolution = [clientwidth, clientheight];
        res.json({ok: true});
        console.log(clientResolution)
    
        // clientResolution is only available inside this function block 
        // where it was declared
    });
    
    // clientResolution is NOT available out here because this 
    // is outside of its declaration scope
    

    如果您对 Javascript 变量的“作用域”概念感到困惑,那么您确实需要学习这些知识才能使用 Javascript 进行编程。这是一个tutorial,它涵盖了许多类型的范围(块、函数、模块、全局)。

    服务器上的客户端状态

    其次,即使您在更高的范围内定义了变量,以便它的值在函数之外可用,这也是设计服务器端代码的错误方法。服务器响应许多不同客户端的需求,因此您不能将属于一个特定客户端的状态存储在模块级别或全局级别的变量中,因为不同的客户端会占用彼此的数据。

    一般而言,您希望将服务器设计为尽可能无状态,因为这样更易于编写和扩展。但是,如果你发现你必须存储一些状态,那么你通常会使用一个“会话”,它是一个存储在服务器上的对象,对于通过 cookie 连接到特定客户端的每个客户端都是唯一的。然后,当您将状态数据放入会话对象中时,它对于该特定客户端将是唯一的。您可以使用 express-session module 开始使用会话对象。

    【讨论】:

      猜你喜欢
      • 2016-07-09
      • 2021-10-30
      • 1970-01-01
      • 2015-07-23
      • 1970-01-01
      • 2016-09-27
      • 2016-07-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多