从NodeJS ExpressJS返回变量



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

我感谢你的帮助:(

这里有多个问题。

可变范围

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

查看我插入您代码的注释:

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编程,这是您真正需要学习的东西。这里的教程涵盖了许多类型的作用域(块、函数、模块、全局(。

服务器上的客户端状态

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

通常,您希望将服务器设计为尽可能无状态,因为这样可以更容易地进行编写和扩展。但是,如果你发现你必须存储一些状态,那么你通常会使用";会话";该对象将是存储在服务器上的对象。然后,当您将状态数据放入会话对象中时,它对于特定的客户端将是唯一的。您可以使用express-session模块开始使用会话对象。

最新更新