Express - 响应中间件未使用

时间:2015-07-24 05:34:10

标签: node.js express

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

我希望通过responseLogMiddleware记录上述错误。但是,记录器既不打印日志也不发送响应。

我没有使用res.json(或)res.send,因为它会绕过中间件刷新响应。

2 个答案:

答案 0 :(得分:1)

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

您应该使用next()来控制下一个处理程序(responseLogMiddleware)。你应该把app.use(responseLogMiddleware)放在你的所有路由器之后。

答案 1 :(得分:0)

试试这个

row2

您需要将中间件与某些路由路径相链接,因为它是路由器级中间件

对于您必须使用的所有路线

<!doctype html> <html> <head> <meta charset="utf-8"> <title>Untitled Document</title> <style> .articles_row { margin-bottom: 12px; color: green; } .article_left { float: left; width: 48%; border: solid 2px #D74447; } .article_right { float: right; width: 48%; border: solid 2px #D74447; } </style> </head> <body> <div class="articles_row" id="row1"> <div class="article_left"> <p>This is left. </p> </div> <div class="article_right"> <p>This is right.</p> </div> </div> <div class="articles_row" id="row2"> <div class="article_left"> <p>This is left. </p> </div> <div class="article_right"> <p>This is right.</p> </div> </div> </body> </html>