简体   繁体   中英

How does callback really work in node js

Below is my code which has two callbacks and one get route

app.get('/login', function(req, res, next) {
     res.sendFile(__dirname + '/public/views/login.html');
});
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");
});

Basically here the two callbacks are for error handling.If I run the app and go to localhost:3000/home ,since there is no route and because of the call backs Ill get the 404 errror.

But if I go to localhost:3000/login ,it is displaying my login.html page but no call backs are getting called.Even though there is no error I mean atleast it should print first console message in the callback.But why it is not calling the callback?

What I read about callbacks is that if you don't specify any path,it gets called for all the routes.But why not here?Can someone take time to read this and clear me if I'm wrong.

This is not about callbacks. It is about how the middleware (plugin/module) architecture work in Express (and incidentally lots of other frameworks, but be warned: not all frameworks work like this).

The real code implemented by Express is modular and a bit more complicated but basically it works something like this:

var middlewares = [];

var app = {
    use: function (callback) {
        middlewares.push({path:"", callback: callback});
    },
    get: function (path, callback) {
        middlewares.push({path: path, callback: callback});
    }
}

So you see, the idea is simple. There really is nothing fancy. .use() is used to add code you want to execute with all paths and .get() is used to add code you want to execute if the path matches.

So we can now process each request to the server by looping through the array:

// WARNING: NOT REAL CODE, this is only meant as an illustration

function processRequest (req, res) {
    for (var i=0; i<middlewares.length; i++) {
        var whatToDo = middlewares[i];

        if (whatToDo.path == "") { // no need to check path
            whatToDo.callback(err, req, res, next);
        }
        else if (whatToDo.path == req.path) { // check if path match
            whatToDo.callback(req, res, next);
        }
    }
}

So that's how it works. Of course, the middlewares are asynchronous so in the real code we can't use the for loop. That's actually what the next() function is for - to loop through the middlewares like a linked list (only, its linked functions). If no next() is called the loop stops.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM