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

339
Vistas
How to properly check HTTP request body and deny it if doesn't match given pattern in a vanilla NodeJS server?

I'm building a server using only nodeJS libraries and methods but I'm having trouble checking the request body format and responding right away with a client error status code type (400-499).

The following code is of a js file of a controller for a type of request supported by my server (I'm using an MVC type architecture):

const { createNews } = require('../useCases/postNewsUseCase'); //useCase file to which the request proceeds if its in good format

const postNews = (req, res) => {
  if (req.method !== 'POST') { //tests if request method is correct
    res.writeHead(405, { 'Contet-type': 'text/plain' });
    res.end();
  }

  let data = '';

  req.on('data', chunk => {
    data += chunk;
  })
  req.on('end', () => {
    const newsBody = JSON.parse(data);

    if (Object.keys(newsBody).toString() !== ['title','content','category'].toString()){
      res.writeHead(400, { 'Contet-type': 'text/plain' });
      res.end();
    } // tests if the request body format matches the expected

    for (let field in newsBody) {
      if ((/^\s*/).test(newsBody[field])){
        res.writeHead(400, { 'Contet-type': 'text/plain' });
        res.end(); // tests if any property is not provided/blank
      }
    }

    createNews(newsBody); //sends the request to the next level which will interact with the DB

    res.end();
  });

}

module.exports = {
  postNews
}

The thing is, if a request body like the following (bad format) is sent, the server proceeds to the useCase level anyway instead of ending the communication between client and server as specified in my tests:

{
    "title":"titulo",
    "content":"conteudo"
}

Can anyone help me? Am I misusing res.end() to end communication and returning the server response?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You can use Joi library. https://github.com/sideway/joi

example of use.

{
  "title": "This is supposed to be a title",
  "content": "There should be some content here."
}

const schema = Joi.object({
    title: Joi.string().min(8).max(30).required(),
    content: Joi.string().min(24).max(255).required(),
 });
over 4 years ago · Santiago Trujillo 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