数组在res.json()中为空,但在res.json()调用之前和之后都存在
Array is empty in res.json() but it exists before and after the res.json() call
我试图通过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主要是异步的。
相关文章:
- 立即返回res.json响应
- 节点.js无法使用 res.json 设置标头错误
- fs.readFile 的替代方法,用于在 Express 中使用 res.json 时加载车把模板
- Express 4 Multer / req.body 和 res.json 未定义
- 如何在公共JS文件中使用通过Express res.render发送的JSON
- Express.js 中 res.send 和 res.json 之间的区别
- res.json在回调函数中不起作用
- Sailsjs-返回res.json();后继续执行;
- 为什么我不能内联调用res.json
- 以值为对象创建JSON格式的res.cookie
- node.js TypeError:路径必须是绝对的,或者指定根目录到 res.sendFile [无法解析 JSON]
- AngularJS控制器如何处理res.json(false)值
- Res.json阻塞了我的node/express服务器
- 从Node + Express API中提取使用res.json发送的信息
- 在nodejs应用中读取res.json
- 数组在res.json()中为空,但在res.json()调用之前和之后都存在
- 猫鼬.找到一个请求.参数数组?res.json是每个值和计数的数组
- 如何将res.json作为回调函数传递
- 我可以使用'res.sendFile'和& # 39;res.json& # 39;在一起
- 优先顺序Javascript/PHP/Jquery Json-从用户那里获取浏览器res