为什么我的中间件没有被快递调用?

时间:2018-04-11 17:13:05

标签: node.js express

我试图为express编写一个简单的中间件:

const express = require('express');

var app = express();

app.use(function(err, req, res, next) {
  console.log('Time:', Date.now());
  req.send("Hello World!");
});

app.listen(3000, () => console.log('Example app listening on port 3000!'));

但是当我在浏览器中打开地址http://localhost:3000时,不会打印日志,也不会返回Hello World!。唯一返回的是带有Cannot GET /的空白页面。有人可以帮我找到我的错误吗?

1 个答案:

答案 0 :(得分:3)

原因是你使用了错误的功能签名。

Express做了一些坦率的愚蠢魔法,以确定它是错误的中间件还是普通的中间件。

你需要使用它:

app.use(function(req, res, next) {
  res.send("Hello World!");  // use res, not req, to send response
});

而不是:

app.use(function(err, req, res, next) {
  req.send("Hello World!");
});

如果function.length === 4,则Express认为它是错误中间件。那是一个愚蠢的设计决定。你并不是第一个在此旅行的人。

表达应该做什么是这样的:

app.error(function(err, req, res) {
  res.send("Hello World!");
});

只需使用其他方法注册错误中间件。