Differences between express.Router and app.get?

前端 未结 8 1029
终归单人心
终归单人心 2020-11-29 14:24

I\'m starting with NodeJS and Express 4, and I\'m a bit confused. I been reading the Express website, but can\'t see when to use a route handler or when to use

8条回答
  •  日久生厌
    2020-11-29 14:57

    Let’s say your application is little complex. So what we do first is we divide the application into multiple modules so that changes in one module doesn't clutter the others and you can keep working on individual modules, but at the end of the day you need to integrate everything into one since you are building a single application. It is like we have one main application and few child applications whose parent is the main application. So when we create the parent application we create one using

    var express = require('express');
    var parent = express();
    

    And to this parent application we need to bring in the child applications. But since the child applications are not totally different applications(since they run in the same context-java term), express provides the way to do it by means on the Expresse's Router function and this is what we do in the each child module file and lets call one such child module as aboutme.

    var express = require('express');
    var router = express.Router();
    /**
    ** do something here
    **/
    module.exports = router;
    

    By module.exports we are making this module available for other to consume and since we have modularized things we need to make the module files available to the parent application by means of node's require function just like any other third party modules and the parent file looks something like this.

    var express = require('express') 
    var parent = express() 
    var child = require(./aboutme)
    

    after we make this child module available to the parent we need to tell the parent application when to use this child application. Lets say when a user hits the path aboutme we need the child application about me to handle the request and we do it by using the Expresse's use method.

    parent.use('/aboutme',  aboutme);
    

    and in one shot the parent file looks like this

    var express = require('express');
    var parent = express();
    var child = require(./aboutme);
    /***
    **do some stuff here
    **/
    parent.use('/aboutme',child);
    

    Above all what the parent can do is it can start a server where as the child cannot. Hope this clarifies. For more information you can always look at the source code which takes some time but it gives you a lot of information. Thank you.

提交回复
热议问题