Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

206
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda