Home > Net >  GET request not working, when variable is initialized with empty array
GET request not working, when variable is initialized with empty array

Time:12-18

I am trying to create a post object which stores the id, title, and comments associated with the post. For now, I am storing data in a variable. When I initialize that variable (Line 7), posts = { }, it works but for posts = [ ] it returns empty array to the frontend.

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');
});

CodePudding user response:

posts can be an array if it is mutated like an array, but if send is bound to enumerate an array parameter in order to serialize it. A prop that's set on the array like posts["some id"] won't count in length, won't be enumerated when it is serialized.

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

To see it not work...

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

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

  • Related