Path mapping (routing) function and control of NODEJS Frame Express

Source: Internet
Author: User

Path mapping (routing) function and control of NODEJS Frame Express

We know that Express is a very good service-side development framework based on NODEJS, this article Csser will provide the express framework of the route and the route control section, the route implements the URL of the client Request path mapping function, Let's translate it into a route or URL map. If you still do not understand, believe that after reading this article will have some harvest.

Routing (URL mapping)

Express uses HTTP actions to provide a meaningful and expressive URL mapping API, for example, we may want to make the URL of the user account look like "/USER/12", and the following example implements such a route, with a placeholder identifier (in this case: ID) The associated value can be obtained by req.params.

App.get ('/user/:id ', function (req, res) {res.send (' user ' + req.params.id);});

In the previous example, when we visited/USER/12, we returned "user", Csser Note: App.get is equivalent to registering a listener on the server to listen for a GET request event, and when the requested URL satisfies the first parameter, the subsequent callback function executes asynchronously.

A route is a simple string that can be internally compiled into a regular expression, such as when/user/:id is compiled, and the internal compiled regular expression string looks like this (simplified):

\/user\/([^\/]+) \/?

To implement a complex point, we can pass in the direct amount of the regular expression because the regular capturing group is anonymous so we can access through Req.params, the first capturing group should be req.params[0], the second should be req.params[1], and so on.

App.get (/^\/users?: \ /(\d+) (?: \. \. (\d+))?)? /, Function (req, res) {res.send (req.params);});

Use the Linux Curl command to test the routes we define:

$ Curl http://cssercom:3000/user[null,null]$ Curl http://cssercom:3000/users[null,null]$ Curl Http://cssercom:3000/ users/1["1", null]$ Curl http://cssercom:3000/users/1..15["1", "15"]

Here are some examples of routes and the associated paths that match them:

"/user/:id"/USER/12 "/users/:id?" /users/5/users "/files/*"/files/jquery.js/files/javascripts/jquery.js "/file/*.*"/files/jquery.js/files/ Javascripts/jquery.js "/user/:id/:operation?" /user/1/user/1/edit "/products.:format"/products.json/products.xml "/products.:format?" /products.json/products.xml/products "/user/:id.:format?" /user/12/user/12.json

In addition, we can submit JSON data by post, and then use Bodyparser middleware to parse the JSON request body and return the JSON data to the client:

var express = require (' Express '), app = Express.createserver (), App.use (Express.bodyparser ()), App.post ('/', function ( Req, res) {res.send (req.body);}); App.listen (3000);

Usually we use placeholders (such as/user/:id) without any restrictions, that is, the user can pass in a variety of data types of ID values, if we want to limit the user ID number, you can write "/user/:id (\d+)", This ensures that only the placeholder data type is a numeric type for the related processing of the route.

Routing control

Multiple routes can be defined in an application, and we can control them to move to the next route, and Express provides the third parameter, the next () function. When a pattern is not matched, the control is turned back to connect (Express is based on the Connect module), and the middleware continues to execute in the order in which they are added in use (). This is true when multiple defined routes may match the same URL, unless a route does not call next () and the response is output to the client, otherwise they are executed sequentially.

App.get ('/users/:id? ', Function (req, res, next) {var id = req.params.id; if (ID) {//A note: If the response content is output to the client here, subsequent URL mappings will not be called} else {next ();//control will be shifted to the next URL-compliant route}); App.get (' /users ', function (req, res) {//do something else});

The App.all () method can apply a single invocation portal to all HTTP actions, which in some cases is useful. Let's use this feature to load a user from our simulation database and assign it to Req.user.

Var express = require (' Express ')   , app = express.createserver (); var  users = [{ name:  ' www.csser.com '  }];app.all ('/user/:id/:op? ',  function (req ,  res, next) {  req.user = users[req.params.id];  if  (Req.user)  {    next ();   } else {    next (new  Error (' cannot find user  '  + req.params.id));   }); App.get ('/user/:id ',  function (req, res) {  res.send (' viewing  '  + req.user.name);}); App.get ('/user/:id/edit ',  function (req, res) {  res.send (' editing  '  +  Req.user.name);}); App.put ('/user/:id ',  function (req, res) {  res.send (' updating  '  +  Req.user.name);}); App.get (' * ',  function (req, res) {  res.send (' What??? ',  404);}); App.listen (3000);
Routing parameter preprocessing

This section is a post-supplement (2011-4-16).

Routing parameter preprocessing can greatly improve the readability of the application code and the validation of the request URL through implicit data processing. If you routinely get generic data from several routes, such as loading user information through/user/:id, we might typically do this:

App.get ('/user/:userid ', function (req, res, next) {User.get (req.params.userId, function (err, user) {if (err) return NE    XT (ERR);  Res.send (' user ' + User.Name); });});

After preprocessing, parameters can be mapped to callback functions, which can provide functions such as validation, mandatory change of values, and even loading data from the database. Next we'll call App.param () and pass in the parameters we want to map to a middleware, and we can see that we've received the ID parameter that contains the placeholder (: userId) value. Here you can load user data and error handling as usual, and can simply turn control to the next preprocessing or routing (path Control) by calling next.

App.param (' UserId ', function (req, res, next, id) {user.get (ID, function (err, User) {if (err) return next (ERR);    if (!user) return next (New Error (' failed to find user ');    Req.user = user;  Next (); });});

This, not only to the above mentioned can greatly improve the readability of the route, but also in the entire application to share the logical implementation of the part, to achieve reuse.

App.get ('/user/:userid ', function (req, res) {res.send (' Csser user is ' + req.user.name ');});

For simple cases such as routing placeholder validation and forced change values, only 1 parameters are passed (1 parameters are supported), and the exception thrown during the period is automatically passed to next (err).

App.param (' number ', function (n) {return parseint (n, 10);});

You can also apply a callback function to multiple placeholders, such as Route/commits/:from-:to: From and: To are numeric types, and we can define them as arrays:

App.param ([' From ', ' to '], function (n) {return parseint (n, 10);});
Conclusion

Through the study of this article, we should have some feeling, nodejs not only can realize our product service end logic, at the same time we can also use JavaScript to do server programming, note is the server, that is to say, We can use JavaScript to customize functionality that was previously only available in Apache. Nodejs still need rewrite? Path mapping is simpler and more powerful, what do you want to rewrite for?

Path mapping (routing) function and control of NODEJS Frame Express

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.