【问题标题】:GET request not working, when variable is initialized with empty arrayGET请求不起作用,当变量用空数组初始化时
【发布时间】: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


【解决方案1】:

posts 可以是一个数组,如果它像数组一样被变异,但如果 send 绑定到枚举数组参数以便序列化它。像posts["some id"] 这样在数组上设置的道具不会计入长度,在序列化时不会被枚举。

  if (type == 'PostCreated') {
    const { id, title } = data;
    // if posts is an array
    posts.push({
      id,
      title,
      comments: [],
    });
  }

看到它不起作用...

let props = [];
let id = "some id";
props[id] = "I'll be lost in serialization";

console.log(props.length); // 0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多