数组在res.json()中为空,但在res.json()调用之前和之后都存在

Array is empty in res.json() but it exists before and after the res.json() call

本文关键字:json res 存在 调用 之后 数组 但在      更新时间:2023-09-26

我试图通过res.json()通过Express发送json响应,但通过res.json()发送的对象中records的值为空。

我有这样一段代码:

stats.activities(params).then(res => {
    processActivities(res, response => {
        console.log(response); // => logs response properly
        globalRes.json({
            ok: true,
            message: '',
            records: response // response is an empty array
        });
        console.log(response); // => logs response properly
    });
});

这是我的console.logs():

[ players: [ [ [Object], [Object], [Object] ] ] ]
[ players: [ [ [Object], [Object], [Object] ] ] ]

下面是我得到的响应(在Postman中):

{
    "ok": true,
    "message": "",
    "records": []
}

你知道是什么原因导致的吗?

这不是一个有效的数组:

[ players: [ [ [Object], [Object], [Object] ] ] ]

数组具有数字索引和长度。你的数组有一个名为player的属性,在调用JSON.stringify时它将被忽略。

下面是演示这个问题的示例:

let a    = [];
a.player = 'jack';
console.log(JSON.stringify(a)); // []

你可能想要一个对象:

let a    = {};
a.player = 'jack';
console.log(JSON.stringify(a)); // {"player":"jack"}

什么是globalRes?通常情况下,你应该使用一个响应变量,该变量在回调时被函数抓取。您可能会尝试一些变通方法,可能是您的控制台。日志在globalRes实际发送后执行。

Node主要是异步的。