NODE JS :: Next() Handler
Next() simple express app example:
var express = require('express');
var app = express();
app.get('/user/:id', function (req, res, next) {
console.log('FIRST request handler');
next();
});
app.get('/user/:id', function (req, res, next) {
console.log('USED request');
res.sendStatus(200);
next();
});
app.get('/user/:id', function (req, res, next) {
console.log('FINAL request handler');
next();
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
});
If you do
http://localhost:3000/user/999
you will see this printed to console:
FIRST request handler
USED request
FINAL request handler
Now if you comment out the call to next()
in the middle handler like this:
app.get('/user/:id', function (req, res, next) {
console.log('USED request');
res.sendStatus(200);
//next();
});
You will see this on the console:
FIRST request handler
USED request
Notice that the last handler (the one that prints FINAL request handler
) does not run. That's because you are no longer telling express to run the next handler.
So it doesn't really matter if your "main" handler (the one that returns 200) was successful or not, if you want the rest of the middlewares to run, you have to call next()
.
When would this come in handy? Let's say you want to log all requests that came in to some database regardless of whether or not the request succeeded.
app.get('/user/:id', function (req, res, next) {
try {
// ...
}
catch (ex) {
// ...
}
finally {
// go to the next handler regardless of what happened in this one
next();
}
});
app.get('/user/:id', function (req, res, next) {
InsertlogsInToDatabase(req);
next();
});
If you want the second handler to run, you have to call next()
in the first handler.
Remember that node is async so it can't know when the first handler's callback has finished. You have to tell it by calling next()
.
Comments
Post a Comment