Reputation: 16821
I'm trying to write a simple middleware for 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!'));
But when I open the address http://localhost:3000
in a browser, the log is not printed and the Hello World!
is not returned. The only thing returned is a blank page with Cannot GET /
. Can someone please help me find my error?
Upvotes: 0
Views: 93
Reputation: 99960
The reason is because you are using the wrong function signature.
Express does some frankly stupid magic to determine if it's error middleware or regular middleware.
You need to use this:
app.use(function(req, res, next) {
res.send("Hello World!"); // use res, not req, to send response
});
instead of this:
app.use(function(err, req, res, next) {
req.send("Hello World!");
});
if the function.length === 4
, then Express considers it to be error middleware. That was a dumb design decision. You are not the first to trip on this.
What express should have done is something like this:
app.error(function(err, req, res) {
res.send("Hello World!");
});
simply use a different method to register error middleware.
Upvotes: 3