Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

334
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda