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

Source: Internet
Author: User

Related reading:

Express 4.X API Translator [i]--application

Express 4.X API translation [II]-Request Chapter

Express 4.X API translation [III]---response

Express 4.X API translation [IV]---router

This is the fourth article of Express 4.0 API translation, the content of this article is mainly router related operation.

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. 2Router.use (function(req,res,next) {3     // ... Some of the intermediate logic operations, like other middleware. 4 next ();5 });6 //when processing any request that ends with "/events"7 //depending on where the router is being used. 8Router.get ('/events ',function(req,res,next) {9     //....Ten});

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

1 // only if 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 varExpress = require (' Express ');2 varApp =Express ();3 varRouter =Express. Router ();4  5 //A simple routing access logger6 //all requests will first touch this middleware7Router.use (function(req,res,next) {8Console.log ('%s%s '%s '), Req.method,req.url,req.path);9 next ();Ten }); One   A //This rule will only be called by the request at the end of path for/bar -Router.use ('/bar ',function(req,res,next) { -     //... Perhaps there are some additional/bar logging available here ... the next (); - }); -   - //is always called +Router.use (function(req,res,next) { -Res.send (' Hello world '); + }); A   atApp.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.

1Router.param (' User ',function(req,res,next,id) {2User.fine (ID,function(err,user) {3         if(err) {4             returnNext (err);5         }6         Else if(!user) {7             returnNextNewError (' Failed to load user '));8         }9  TenReq.user =user; One next (); A     }); - }); -   the //This route uses a parameter named ': User ' - //this will cause the ' user ' parameter callback function to be triggered -Router.get ('/users/:user ',function(req,res,next) { -     //Req.user will be defined when executed here +     //If there are any errors or normal error handling, it will be triggered.  -    //This function will not be executed.  +});

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.

1Router.param (function(NAME,FN) {2     if(FNinstanceofRegExp) {3         return function(req,res,next,val) {4              varcaptures;5             if(Captures =fn.exec (String (val))) {6Req.params[name] =captures;7 next ();8}Else{9Next (' Route ');Ten             }       One         } A     } -});

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

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

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 varRouter =Express. Router ();2  3Router.param (' user_id ',function(req,res,next,id) {4     //The following are sample users that can be from the database .... Get in wait5Req.user = {6 Id:id,7Name: ' TJ '8     };9 next ();Ten }); One   ARouter.route ('/user/:user_id ') -. All (function(req,res,next) { -     //running in said HTTP dynamic request the     //It can be thought of as a specific routing middleware - }) -. Get (function(req,res,next) { - Res.json (req.user); + }) -. put (function(req,res,next) { +     //just an example, it could be an update user AReq.user.name =Req.params.name; at     //Save user .... Wait - Res.json (req.user); - }) -. Post (function(req,res,next) { -NextNewError (' not implemented ')); - }) in.Delete(function(req,res,next) { -NextNewError (' not implemented ')); to});

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.