I got the sample node js code using expressgenerator ,which by default got the error handling code as follows
app.use(function (req, res, next) {
console.log("first callback 1");
var err = new Error('Not Found');
err.status = 404;
next(err);
console.log("first callback 2");
});
app.use(function (err, req, res, next) {
// set locals, only providing error in development
console.log("second callback");
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
console.log("error send");
});
I've added few console.logs in those error handling callbacks.What I understood from the callbacks is that since we didnt provided any route here these two call backs will be called for all the routes.
Now in my code I've added one route as
app.get('/login', function(req, res, next) {
res.sendFile(__dirname + '/public/views/login.html');
});
Now when I run my app and go to localhost:3000/home which is not there in my app.js.So it is printing following
first callback 1
second callback
error send
first callback 2
first callback 1
second callback
error send
first callback 2
Question 1:Why the console log is getting printed twice?It should not print after firstcallback 2.
Now when I go to localhost:3000/login it renders me login.html page as the route is present but there are no console logs in my server side.
Question 2:Why the first console "first callback 1" is not getting printed.Since the callback is for all routes and in this case since it doesnt have error atleast it should print my first console..But not..Why it is not doing that callback??
Can someone explain this and how callbacks are called here and use of that next()