Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

204
Views
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');
});
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!