user2879704
user2879704

Reputation:

Express - response middleware is not used

var log = console.log
var responseLogMiddleware = function(req, res, next) {
  log("inside the response middleware")
  res.send()
}
app.get('/', function(req, res) {
  res.status(404)
  res.body = {"status" : "notDone"}
})
app.use(responseLogMiddleware)

app.listen(8003);

I expected the above error to be logged via responseLogMiddleware. But,neither the logger is printing the logs nor the response is sent back.

I am not using res.json (or) res.send, since it flushes out the response bypassing the middlewares.

Upvotes: 0

Views: 64

Answers (2)

BlackMamba
BlackMamba

Reputation: 10252

var log = console.log
var responseLogMiddleware = function(req, res, next) {
    log("inside the response middleware");
    return res.send();
}

app.get('/', function(req, res, next) {
  res.status(404)
  res.body = {"status" : "notDone"};
  next();
})
app.use(responseLogMiddleware);

You should use next() topass control to the next handler(responseLogMiddleware). And you should put app.use(responseLogMiddleware) after all your router.

Upvotes: 1

Sushant
Sushant

Reputation: 1414

try this

app.use('/',responseLogMiddleware)

You need to link your middleware with some route path because its a router level middleware

for all routes you have to use

app.use('*',responseLogMiddleware)

Upvotes: 0

Related Questions