Simple analysis of node. JS Express Routing

Source: Internet
Author: User

This 2 days to see a little node+express route source has a little prospect, summed up

For App.get,

First, a class diagram is given:

Figure 1

Note that there is a stack for each route, and the layer is stored in the stack.

There are three files in the routing system:

Figure 2

Where Layer.js,route.js is the module of the class in Figure 1.

Application.js are only operating on the outer layer router

The outer route is for middleware, and the inner route is for the middleware link

In Index.js, I think the route has also been encapsulated, the following is the important factory method

Proto.route =functionroute (Path) {
Outer route Build
var route = new route (path);//create inner layer routevarLayer =NewLayer (path, {sensitive: This. CaseSensitive, Strict: This. Strict, End:true}, Route.dispatch.bind (route)); Layer.route=route;//Each outer layer refers to an inner route to form a circular reference This.stack.push (layer);
Add the resulting layer to the outer stack
returnroute;};
implementation of all HTTP predicate methods for the outer route
//
Methods.concat (' all '). ForEach (functionmethod) {function(path) { var route = This . Route (path)//outer layer plus one level 1);// Call the inner router predicate to add a layer returnthis; };});
 app.lazyrouter = function   Lazyrouter () {  if  (! ._router) { this . _router = Span style= "color: #0000ff;" >new   Router ({casesensitive:  this . Enabled (' Case sensitive routing '  this . Enabled (' Strict routing '  this . _router.use (Query (this .    Get (' Query parser fn '  this . _router.use (Middleware.init (  This  
The implementation of the App.use middleware can be seen using the use method of the routing system.
App.use =functionUse (FN) {varOffset = 0; varPath = '/'; //default path to '/'  //disambiguate App.use ([fn])  if(typeoffn!== ' function ') {    vararg =fn;  while(Array.isarray (ARG) && arg.length!== 0) {arg= Arg[0]; }    //First Arg is the path    if(typeofArg!== ' function ') {offset= 1; Path=fn; }  }  varFNS =Flatten (slice.call (arguments, offset)); if(Fns.length = = 0) {    Throw NewTypeError (' App.use () requires middleware functions '); }  //Setup Router   This. Lazyrouter (); varRouter = This. _router; Fns.foreach (function(FN) {//non-express App    if(!FN | |!fn.handle | |!fn.set) {return router.use (path, FN);//outer route } debug ('. Use app under%s ', path); Fn.mountpath=path; Fn.parent= This; //restore. App property on req and res  router.use (path, function Mounted_app (req, res, next) {///outer route var orig = Req.app; Fn.handle (req, res, function (err) {req.__proto__ = Orig.request; res.__proto__ = Orig.response; Next (ERR); }); }); //mounted an appFn.emit (' Mount ', This); },  This); return  This;};

The use method of the outer route is called, and then the use method of the route is seen: (index.js)

Proto.use =functionUse (FN) {varOffset = 0; varPath = '/'; //default path to '/'  //disambiguate Router.use ([fn])  if(typeoffn!== ' function ') {    vararg =fn;  while(Array.isarray (ARG) && arg.length!== 0) {arg= Arg[0]; }    //First Arg is the path    if(typeofArg!== ' function ') {offset= 1; Path=fn; }  }  varCallbacks =Flatten (slice.call (arguments, offset)); if(Callbacks.length = = 0) {    Throw NewTypeError (' Router.use () requires middleware functions '); }   for(vari = 0; i < callbacks.length; i++) {    var fn = callbacks[i]; if(typeoffn!== ' function ') {      Throw NewTypeError (' Router.use () requires middleware function but got a ' +GetType (FN)); }    //Add the middlewareDebug (' Use%s '%s ', path, Fn.name | | ' <anonymous> '); var layer = new Layer (path, {sensitive:this.caseSensitive, strict:false, End:false }, fn); //outer route build layer.route=undefined;  This . Stack.push (layer); }  return  This;};

It can be seen that each layer corresponds to a function, with multiple layers in a stack. And the path is passed into the layer, and each call to use creates an outer layer.

Take a look at App.get/post and other methods

Methods.foreach (function(method) {App[method]=function(path) {if(method = = = ' Get ' && arguments.length = = = 1) {      //app.get (setting)      return  This. Set (path); }     This. Lazyrouter (); var route = this._router.route (path);//outer layer added, add an outer layer route[method].apply (route, Slice.call (arguments, 1)); return  This; };});

Methods is an array of all HTTP verbs and so on, all apps. Method applies to the predicate of the inner router

, call the inner layer router, for the HTTP predicate of the inner layer router:

Methods.foreach (function(method) {Route.prototype[method]=function(){    varHandles =Flatten (Slice.call (arguments));  for(vari = 0; i < handles.length; i++) {      varHandle =Handles[i]; if(typeofHandle!== ' function ') {        varType =Tostring.call (handle); varmsg = ' Route ' + Method + ' () requires callback functions but got a ' +type; Throw NewError (msg); } debug ('%s%s ', method, This. Path);  var layer = layer ('/', {}, handle);//Inner Layer Layer.method = method;  This.methods[method] = true;  This . Stack.push (layer);//inner layer }return  This; };});

All get/post are added layer on the inner router stack.

Visible whether it is use, or get/post end is to increase the layer, for use, increase the outer layer, for get/post, increase the outer layer, and increase the inner layers

Simple analysis of node. JS Express Routing

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.