Home > OS >  Express custom json response
Express custom json response

Time:10-17

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?

CodePudding user response:

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})
}

CodePudding user response:

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);
  • Related