Nodejs Express 4.X Chinese API 4---Router

Source: Internet
Author: User

Router ()

A router is an isolated middleware and an instance of a route. A router can be considered a "mini" application and can only execute middleware and routing options. Every express program will have a built-in application router.

The router behaves as if it were a middleware itself, which you can use either through the application or within other routing rules.

Create a new router by using "Express." Router () "

1 var router = Express. Router ();

Routers can be middleware, and adding HTTP dynamic routes is like a program.

1//Adapt any routing rules to this router. 2 Router.use (function (req,res,next) {3     //... Some of the intermediate logic operations, like other middleware. 4     Next (); 5}); 6//When processing any request ending with "/events" 7//depends on where the router is being used. 8 Router.get ('/events ', function (req,res,next) {9     //.... 10});

Then you can use a router for a specific root URL to separate your routes into files and even mini apps.

1//Only when the request "/calendar/*" will be sent to "router" 2 app.use ('/calendar ', router);

Router.use ([path],function)

Using the given middleware function, the mount path with optional parameters is mounted by default on the '/'

The middleware is like a pipeline, where the request begins with the first defined middleware, down the line, and matches every route that satisfies the criteria.

1 var express = require (' Express '); 2 var app = Express (); 3 var router = Express. Router (); 4   5//A simple routing access logger 6//All requests will first touch this middleware 7 router.use (function (req,res,next) {8     console.log ('%s%s%s '), Req.method,req.url,req.path); 9     Next ();  12//This rule will only be called by the end of path for/bar request Router.use ('/bar ', function (req,res,next) {+     /... Perhaps there are some additional/bar logging available here ...  18//is always called router.use (function (req,res,next) {     res.send (' Hello World '); 21}); 22  app.use ('/foo ', router); App.listen (3000);

The "Bound" path is stripped and the middleware functions are not visible. This primarily affects the middleware that is bound to be executed whenever the suffix is determined, regardless of what the prefix looks like.

In this way, the order in which the middleware is "defined" using "router.use ()" will be very important, and they are called sequentially, so this will define the priority of the middleware. For example, "Express.logger ()" is usually the middleware you want to call first, to record all requests.

1 Router.use (Logger ()), 2 Router.use (express.static (__dirname + '/public ')), 3 router.use (function (req,res) {4     Res.send (' Hello '); 5});

Now if you do not want to log requests for static files, but want to continue to record routing and middleware requests, you can simply move the static file definition to logger ().

1 Router.use (express.static (__dirname + '/public ')), 2 router.use (Logger ()), 3 router.use (function (req,res) {4     Res.send (' Hello '); 5});

Another specific example is the use of a multi-file directory to provide static file services, giving "/public" precedence over other directories.

1 App.use (express.static (__dirname + '/public ')), 2 App.use (express.static (__dirname + '/files ')), 3 App.use ( Express.static (__dirname + '/uploads '));

Router.param ([name],callback)

The logical map to the parameter. For example, when ': User ' exists in the routing path, you can map the user load logic to automatically provide req.user for this route, or perform parameter input validation.

The following code snippet illustrates how callback is like middleware, so it supports asynchronous operations, but if the value of this parameter is named ID here. An attempt was performed to load the user information and then assign it to Req.user, otherwise pass an error to next (err).

It is important to realize that any route triggered by the named parameter callback function will be executed sequentially if Next is not passed an error at the previous level.

1 router.param (' User ', function (req,res,next,id) {2     user.fine (id,function (err,user) {3         if (err) {4             Return next (ERR); 5         } 6         else if (!user) {7             return next (' Failed to load user '); 8         } 9         req.user = user;11         next ();     ); 15//  This route uses the parameter named ': User ' 16//This will be caused by the ' user ' parameter callback function will be triggered by router.get ('/users/:user ', function (Req,res, Next) {     //req.user will be defined when it is executed here     //If there are any errors or normal error handling will be triggered.    //This function will not be executed. 21});

Or you will only pass a callback function, in which case you will have the opportunity to change the API of Router.param (). For example, Express-params defines the following callback function, you can limit the parameters given by the regular expression.

This example is a bit advanced, check whether the second parameter is a regular expression, and return a callback function that behaves like the "user" parameter example.

1 Router.param (function (NAME,FN) {2     if (fn instanceof RegExp) {3         return function (req,res,next,val) {4              var Captures 5             if (captures = Fn.exec (String (val))) {6                 req.params[name] = captures; 7                 next (); 8             }else{9                 Next (' Route ');         }12     }13});

This method can be used to verify the validity of the parameters, or they can be parsed to the provided capture group.

1 router.param (' id ',/^\d+$/); 2   3 router.get ('/user/:id ', function (req,res) {4     res.send (' user ' + Req.params.id); 5}); 6   7 Router.param (' Range ',/^ (\w+) \.\. ( \w+)? $/); 8   9 Router.get ('/range/:range ', function (req,res) {ten     var range = req.params.range;11     res.send (' from ' + range[1] + ' to ' + range[2]); 12});

The Router.use () method also supports named parameters, so your other routing rule mount points can also use this named parameter.

router.route (path)

Returns an instance of a route that you can use to handle HTTP dynamic requests using optional middleware. Using Router.route () is a recommended way to avoid duplicate routing naming and spelling errors:

Based on the previous example of Router.param (), we see that Router.route () allows us to easily specify various HTTP dynamic handlers.

1 var router = Express. Router (); 2   3 Router.param (' user_id ', function (req,res,next,id) {4     //Below is a sample user, can be from database .... Get 5     req.user = {6         id:id, 7         name: ' TJ ' 8     }; 9     next ();  Router.route ('/user/:user_id ') All (function (req,res,next) {     ///Run said HTTP dynamic request (     S//can be considered to be a specific routing middleware). Get (function (Req,res,next) {     Res.json (req.user)). Put (function (req,res,next) {     ////is just an example, can be updated User:     req.user.name = req.params.name;23     //save user ....     Res.json (Req.user), (Req,res,next) (     new Error (' not implemented '), 28}), and 29 . Delete (function (req,res,next) {     new Error (' not implemented ')); 31});

The method re-uses '/users/:user_id ' for different HTTP dynamic request paths and add handlers.

router. VERB (Path,[callback...],callback)

Router. The VERB () method provides the routing functionality in Express, where the VERB is one of the HTTP dynamic requests, as if Router.post (). A variety of callback functions can be given, all will be treated equally, this behavior is like middleware, but the difference is that these "middleware" can call next (' Route ') to bypass the rest of the callback function. This mechanism can be used to perform prerequisite alignments and then pass control to subsequent alignments when there is no continuation of the matching route.

The following code snippet demonstrates the simplest route definition. Express escapes the path to a regular expression, which is used internally to match incoming requests. The request string will not be considered during the execution of the match, such as "GET/" will match the following rule, and the same "/get/?name=tobi" will also be matched.

1 router.get ('/', function (req,res) {2     res.send (' Hello World '); 3});

Regular expressions can also be used, and if you have some special restrictions, regular expressions can be quite useful, such as the following code will match "get/commits/71dbb9c" and also match "get/commits/71dbb9c." 4c084f9″.

1 Router.get (/^\/commits\/(\w+) (?: \. \. (\w+))? $/,function (req,res) {2     var from = Req.params[0];3     var to = req.params[1] | | ' HEAD '; 4     res.send (' Commit range ' + from + ' ... ' + to); 5});

Transferred from: http://www.90it.net/expressjs-api-4-zh-cn-router.html

Nodejs Express 4.X Chinese API 4---Router

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.