Tran Triet
Tran Triet

Reputation: 1307

Nodejs Express how to write middleware to handle all response

In node JS Express, we can write middlewares to intercept requests to either

  1. Call the next middleware in the chain by invoking next
  2. End the chain by calling res.send or similar functions provided by res

That means, everytime we want to end a request and send a response in a particular middleware, we have to add (at least) the below snippet.

res.send();

Are there ways to write a response frame middleware like this:

responseFrame = (res,req,responseData) => {
    res.send(responseData);
}

and insinde route.js, use this middleware on all path

app.use(responseFrame);

Then, we simply have to end any middleware with next(), as long as we define the correct routes, Express will take care of sending the response (if the next middleware is the responseFrame)

Upvotes: 2

Views: 5437

Answers (1)

Ishmeet Singh
Ishmeet Singh

Reputation: 1246

You can use res.locals for that.

https://expressjs.com/en/api.html#res.locals

Upvotes: 1

Related Questions