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

325
Views
¿Cómo verificar correctamente el cuerpo de la solicitud HTTP y negarlo si no coincide con el patrón dado en un servidor Vanilla NodeJS?

Estoy construyendo un servidor usando solo bibliotecas y métodos de nodeJS, pero tengo problemas para verificar el formato del cuerpo de la solicitud y responder de inmediato con un tipo de código de estado de error del cliente (400-499).

El siguiente código es de un archivo js de un controlador para un tipo de solicitud compatible con mi servidor (estoy usando una arquitectura de tipo MVC):

 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 }

La cuestión es que, si se envía un cuerpo de solicitud como el siguiente (formato incorrecto), el servidor procede al nivel de caso de uso de todos modos en lugar de finalizar la comunicación entre el cliente y el servidor como se especifica en mis pruebas:

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

¿Alguien puede ayudarme? ¿Estoy haciendo mal uso de res.end() para finalizar la comunicación y devolver la respuesta del servidor?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Puedes usar la biblioteca Joi. https://github.com/sideway/joi

ejemplo de uso

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