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

151
Visualizações
Express custom json response

I want to send a custom json response on each request at the end like:

{
  "message": "Something",
  "type": "success",
  "payload": /*object, array, anything else */
}

What I can do is at the end of each request use:

res.status(200).json({message: 'Something', type: 'success', payload});

If for some reason I want my responses to have another format, I have to go and change each res.json, which is bad.

But since I know all my responses will have this format, is there any way to create a middleware and pass some variables like payload, message, type which gets executed at the end of each request?

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

0

It is possible to create a midleware for the reponse

router.get('/some-route', controller.someFunction, resposeMiddleware)

You would need to pass the response as an argument on the next call

someFunction (req, res, next) => {
    res.local.payload = {/* some data */}
    next()
}

the resposeMiddleware would be something like this

const resposeMiddleware = (req, res) => {
      const { payload } =  res.local
      res.status(200).json({message: 'Something', type: 'success', payload})
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Create a helper method like bellow (successResponse.js). You can also set any property to default.

    successResponse = (res, statusCode, message, data) => {
      res.status(statusCode || 200).json({
      code: statusCode || 200,
      message: message || "success",
      data: data || {},
    });
   };

   module.exports = successResponse;

now in your controller just import successResponse and use it like

successResponse(res, 200, "Your Success message", data);
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