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

327
Views
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 answers
Answer question

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 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!