Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading