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

99
Visualizações
How to write independent/isolated express middleware with access to raw request body

I am trying to write an Express middleware that has access to the raw request body. So something like this (actually works and) would be ideal:

const middleware = [
  express.raw({ type: '*/*' }),
  (req, res, next) => {
    digest(req.body);
    next();
  },
];

However, this approach means the req.body has now been streamed/processed and is now unavailable to any handler or middleware following my middleware:

app.post(route, middleware, (req, res) => res.send(req.body)); // returns `{}`

I would it to be possible to use my middleware with other body parsers. So this should be ok:

app.use(express.json());
app.post(route, middleware, (req, res) => res.send(req.body)); // should return the JSON body posted not `{}`

As well as this:

app.post(route, middleware, express.json(), (req, res) => res.send(req.body)); // should return the JSON body posted not `{}`

Is it possible to:

  • use middlewares in the manner I am attempting here (i.e. using more than one in succession)?
  • get hold of the raw body by a means other than express.raw({ type: '*/*' })?
  • reset the request body after I am done with it so other handlers and middlewares can access it like my middleware had never been used?

I have expanded these snippets into a failing test in this repository if the above is not clear enough and would appreciate any help or pointers.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

So with a bit more research (and sleep) I think my approach here is probably incorrect.

A more appropriate solution would be to use the verify option of the relevant body parser which gives you access to the buffer:

app.use(express.json({ verify: (req, res, buf, encoding) => digest(buf) || throw 'Invalid Digest' }));
app.post(route, (req, res) => res.send(req.body));
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