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

189
Visualizações
How to detect if request body was sent or not?

I'm working with express + json body parser. For validation purposes I need to distinguish between

  • empty object request body was sent by the user ({})
  • no request body was sent by the user

as I'm trying to provide reasonable error messages, and in one case I need to instruct the user to add missing fields, while in the other case they might not even be aware that the request body should be sent, and the priority is warning them about this.

This to me seems impossible currently, as the json body parser sets request.body to {} in case no request body was provided, reference:

https://github.com/expressjs/body-parser/blob/master/lib/types/json.js#L72

My question is, while using the json body parser, is it possible to detect if the request body was actually sent by the client or not? So how would I implement a function like this:

import { Request } from 'express'

function didTheUserSendRequestBody(request: Request): boolean {
  // What do?
}

Which returns true when my endpoint is hit like this:

curl -X POST http://localhost:5000/foo 
   -H "Content-Type: application/json"
   -d '{}'  

And false for this:

curl -X POST http://localhost:5000/foo 
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Body-parser json has option verify . It can check raw data at here.

 app.use(express.json({ verify: (req, res, buf, encoding) => { 
// check buff is empty ? and attach result to req ? 
} }))

with verify is function with 4 argument : "where buf is a Buffer of the raw request body"

https://github.com/expressjs/body-parser#verify

about 4 years ago · Juan Pablo Isaza Relatório

0

maybe you can just check the submitted content type, if the user doesn't attach it then the default value will be "undefined".

function didTheUserSendRequestBody(request: Request): boolean {
  if (!request.get('Content-Type')) {
    // return any message
  }
}
about 4 years ago · Juan Pablo Isaza Relatório

0

The easiest way I'm aware of is by checking if req.body is truthy

function didTheUserSendRequestBody(request: Request): boolean {
  if(req.body){
    // Do stuff
  }
}

According to https://developer.mozilla.org/en-US/docs/Glossary/Truthy MDN, an empty object '{}' is truthy. If there is no body sent, it should be undefined when you try to access req.body, which is falsy.

See https://expressjs.com/en/api.html#req for more details

about 4 years ago · Juan Pablo Isaza 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