Analysis on express route (continued)

Source: Internet
Author: User

In the previous article, I analyzed the express routing mechanism. This time, I mainly added some things that I didn't talk about.

As mentioned earlier, the router is a middleware container and the route is a routing middleware. Each of them maintains a stack array, which stores layers. The layer is a data structure that encapsulates the middleware. In fact, the router can not only store general middleware, but also store the router, which can be seen in the source code, because the router constructor returns a router function, the middleware also requires a handler (function) to generate. If the handler returned by router () is passed as a parameter to the middleware generation method, it is equivalent to storing a router middleware in the router, but the two routers are two different instances. App. the router is the top-level, which can contain a new router. The new router is added to the app as a middleware. due to the structure design of the router, you can access each middleware processing program in the router, including each middleware in the nested router. This usage is included in the project model generated by the express-e projectname command. The following is the app. js file under the projectname project root directory (not the express root directory:

VaR express = require ('express '); var Path = require ('path'); var favicon = require ('serve-favicon '); vaR logger = require ('Morgan '); var cookieparser = require ('cookie-parser'); var bodyparser = require ('body-parser '); vaR routes = require ('. /routes/Index'); var users = require ('. /routes/Users '); var FS = require ('fs'); var APP = Express (); // view engine setupapp. set ('view', path. join (_ dirname, 'view ') ); App. set ('view engine ', 'ejs'); // uncomment after placing your favicon in/Public // app. use (favicon (_ dirname + '/public/favicon. ICO '); app. use (logger ('dev'); // from here, add the middleware. Because it has not been added before, a router will be instantiated, two middleware (query and init) will be added during instantiation, so this middleware is the third app. use (bodyparser. JSON (); app. use (bodyparser. urlencoded ({extended: false}); app. use (cookieparser (); app. use (Express. static (path. join (_ dirname, 'public'); app. Use ('/', routes); // routes is ". /routes/index. the router instance created in the JS file, that is, the new routerapp is added to the top-level router through this code. use ('/users', users); // var COUNT = routes. stack. length; var COUNT = app. _ router. stack. count; var content = ""; console. log (count);/* For (VAR I = 0; I <count; I ++) {content + = dump_obj (routes. stack [I]) + "\ r \ n"; console. log (App. _ router. stack [I]) ;}; */console. log (App. _ router. stack [7]); // output a special Middle in the top-layer Router, That is, the app. the routes added by the use ('/', routes) statement. This middleware is also the router object/* fs.writefile('message.txt ', content, function (ERR) {If (ERR) Throw err; console. log ('It \'s saved! ') ;}); Function dump_obj (myobject) {var S = ""; for (VAR property in myobject) {S = S + "\ n" + property + ": "+ myobject [property];} return s ;}*/
// Catch 404 and forward to error handlerapp. use (function (req, res, next) {var err = new error ('not found'); err. status = 404; next (ERR) ;}); // error handlers // development error handler // will print stacktraceif (App. get ('enabled') = 'development') {app. use (function (ERR, req, res, next) {res. status (err. status | 500); Res. render ('error', {message: Err. message, error: Err});} // production error handler // No stacktraces leaked to userapp. use (function (ERR, req, res, next) {res. status (err. status | 500); Res. render ('error', {message: Err. message, error :{}}) ;}; module. exports = app;

The following is the./routes/index. js code. A new router object is instantiated in it, and five middleware Products are added to the object.

VaR express = require ('express '); var router = Express. router (); // a new router is instantiated here, and the app (application. JS) in the app. use () or app [Method] can ensure that there is only one router instance in the app, but we can still manually create a new router, app. the router is actually the top-layer middleware container. It can only have one var users = {'byvoid': {name: "carbo", website: 'http: // www.byvoid.com '}}; /* --------- Test start is the test code. Add the middleware to the newly created router and output it for verification later --------- */var route = router. route ('/user'); route. get (function (req, res, next) {}, function (req, Res) {}); // two processing functions are added to the first middleware, the following output will verify the router. all ('user/: username', function (req, res, next) {If (users [req. params. username]) {next ();} else {next (New error (req. params. username + 'does not exist. ') ;}}); router. get ('/user/: username', function (req, Res) {res. send (JSON. stringify (users [req. params. username]);});

router.get(‘/user/:username‘,function(req,res){    res.send(‘user:‘ + req.params.username);});
/*--------- test end -----------*/
 
/* GET home page. */router.get(‘/‘, function(req, res) {  res.render(‘index‘, { title: ‘Express‘ });});module.exports = router;

The output after running is as follows:

The newly created router (this is only used as a middleware ):/*Five middleware items are added to the router object. We can see that there are two elements in the stack of the first middleware, which correspond to the above Code. Orange is used here.*/

{Path: '/user ',

STACK:

[{Handle: [function],

Name: '<anonymous> ',

Params: undefined,

Path: undefined,

Keys: [],

Regexp:/^ \/? $/I,

Method: 'get '},

{Handle: [function],

Name: '<anonymous> ',

Params: undefined,

Path: undefined,

Keys: [],

Regexp:/^ \/? $/I,

Method: 'get'}],

Methods: {Get: true }}

{Path: 'user/: username ',

STACK:

[{Handle: [function],

Name: '<anonymous> ',

Params: undefined,

Path: undefined,

Keys: [],

Regexp:/^ \/? $/I,

Method: Undefined}],

Methods: {_ all: true }}

{Path: '/user/: username ',

STACK:

[{Handle: [function],

Name: '<anonymous> ',

Params: undefined,

Path: undefined,

Keys: [],

Regexp:/^ \/? $/I,

Method: 'get'}],

Methods: {Get: true }}

{Path: '/user/: username ',

STACK:

[{Handle: [function],

Name: '<anonymous> ',

Params: undefined,

Path: undefined,

Keys: [],

Regexp:/^ \/? $/I,

Method: 'get'}],

Methods: {Get: true }}

{Path :'/',

STACK:

[{Handle: [function],

Name: '<anonymous> ',

Params: undefined,

Path: undefined,

Keys: [],

Regexp:/^ \/? $/I,

Method: 'get'}],

Methods: {Get: true }}

9

Top-layer router (middleware container):/* The following is the 7th middleware in the top-layer router. The middleware is also a router, and the blue part is the layer that encapsulates the sub-router, the stack in the sub-router contains five routing middleware, that is, the five output above. The sub-router is the property value of the handler (middleware processing program, that is to say, this sub-router is added to the app as a general middleware. */In the router */

{Handle:

{[Function: Router]

Params :{},

_ Params: [],

Casesensitive: undefined,

Mergeparams: undefined,

Strict: undefined,

STACK: [[object], [object], [object], [object], [object]},

Name: 'router ',

Params: undefined,

Path: undefined,

Keys: [],

Regexp: {/^ \/? (? =\/ | $)/I fast_slash: true },

Route: Undefined}

Since app. the router object can be added to the router, so we can create a new JS file to add custom middleware and instantiate a router object in the JS file, write the routing registration code or the Add code of the non-routing middleware to this file, export the router object, and finally in the app. add the router to the app in Js. in the router.

Analysis on express route (continued)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.