【发布时间】:2022-01-20 21:02:38
【问题描述】:
我正在尝试创建一个帖子对象,该对象存储与帖子关联的 id、标题和 cmets。现在,我将数据存储在一个变量中。当我初始化该变量时(第 7 行), posts = { },它可以工作,但是对于 posts = [ ],它会将空数组返回到前端。
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
app.use(bodyParser.json());
app.use(cors());
const posts = [];
app.get('/posts', (req, res) => {
console.log(posts);
res.send(posts);
});
app.post('/events', (req, res) => {
const { type, data } = req.body;
if (type == 'PostCreated') {
const { id, title } = data;
posts[id] = {
id,
title,
comments: [],
};
}
if (type == 'CommentCreated') {
const { id, content, postId } = data;
const post = posts[postId];
post.comments.push({ id, content });
}
res.send({ status: 'Event Received' });
});
app.listen(4002, (req, res) => {
console.log('Listening on Port 4002');
});
【问题讨论】:
-
你能详细说明你的问题吗?就像您尝试发送的
posts中的数据一样。 -
为什么要在 web api 处理程序之外定义 post 数组?
-
如果您使用数字以外的任何字符作为标识符,它将不适用于数组: const items = [];项目['abc'] = '传说'; JSON.stringify(items) === '[]';
-
@stdob-- 可能是这样,因为所有 id 都是数字字母格式。
-
@DipanshuKumarSuman 帖子:{ id: "rav", title: ""291, cmets: [ ]}
标签: javascript node.js arrays express