How is the morgan middleware able to output the statusCode of the response?

30 Views Asked by At

I understood middleware as functions that you chain behind your actual method-functions to output some information. Upon discovering the 'morgan' package, I realized that it retrieves the correct status code even though it should have no idea about the statusCode the next function yields after passing its req+res to the next function.

I tried to code that by myself and created a similar middleware quite easily. I found a 'statusCode' attribute, which is probably the default one."

Here is my Code:

app.use((req, res, next) => {
  const { url, method } = req;
  console.log(method, url, res.statusCode, util.getTime());
  next();
});

and the reaction to a delete-request:

above code: DELETE /user/17 200 0:51.21.226
morgan:     DELETE /user/17 404 222.601 ms - 48
0

There are 0 best solutions below