我正在用Express.js开发一个应用编程接口。在getAll函数中,我希望返回一个记录数组以及记录总数。这是我返回的响应:
const users = await User.getAll()
const total = users.length
const response = users
return res.json(response).status(200)其格式为[{user1},{user2},{user3}]。如何将总计附加到此格式的{ data: {Record[]}, total: {int} }
我试过了,但它在每个用户中添加了一个带有序号的键。
const users = await User.getAll()
const total = users.length
const response = {
...users,
total
}
return res.json(response).status(200)发布于 2019-10-17 18:37:20
const users = await User.getAll();
return res.json({ data: users, total: users.length }).status(200);发布于 2019-10-17 18:36:57
您正在对象中使用数组扩展,其代码为:
const response = {
...users,
total,
}通过这样做,您试图将数组的所有元素添加到一个对象中,这是不可能的。但是您可以使用您自己建议的格式:
const response = {
data: users,
total: total,
}
return res.json(response).status(200);发布于 2019-10-17 18:44:36
...users在这里造成了痛苦。当您使用扩展操作符时,它允许迭代器(这里是您的users对象)展开。下面应该可以按照你期望的方式工作。
const users = await User.getAll()
const total = users.length
const response = {
users,
total
}
return res.json(response).status(200)https://stackoverflow.com/questions/58430508
复制相似问题