• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Pruebas Online
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

103
Vistas
NodeJS without frameworks: findById

I'm beginner and trying to make a function findByID with NodeJS and JSON file as a database without frameworks, code:

const http = require("http");
const url = require("url");
const fs = require("fs");
const querystring = require("querystring");

const data = fs.readFileSync("./data/data.json");
let todos = JSON.parse(data);
    const server = http.createServer((req, res) => {
        const urlparse = url.parse(req.url, true);
      if (urlparse.pathname == "/todos" && req.method == "GET") {
          const search = urlparse.search;
          if (search) { 
            const [, query] = urlparse.search.split("?");
            const data = querystring.parse(query);
            todos = todos.filter((todo) =>  todo.id === data.id);
            res.end(JSON.stringify(todos, null, 2));
          }
        }})

When I check with postman for the first time everything is fine. 1st request

When I check the second time in the response window there is an empty array.2nd request

Each request used a different id.

almost 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I dont see todos defined so I assume it’s global, this line is then mutating it every request:

todos = todos.filter((todo) =>  todo.id === data.id);

Another thing is if id is unique you could use todos.find to just get the first match.

So instead use a new variable and find:

const todoMatch = todos.find((todo) =>  todo.id === data.id);
almost 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda