1

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

2
  • Never rely on the order of things that might sometimes be synchronous and might sometimes be asynchronous - see blog.izs.me/post/59142742143/designing-apis-for-asynchrony Commented Mar 28, 2017 at 15:28
  • ok @BenjaminGruenbaum..what about the 2nd question why it didnt went in to that first callback and printed that first console? Commented Mar 29, 2017 at 7:53

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.