Detailed explanation of node. js framework express's path ing (Routing) function and example code of control

Source: Internet
Author: User
This article mainly introduces the path ing (Routing) function and control of NodeJS framework express, which has some reference value. If you are interested, you can refer to it. This article mainly introduces the detailed description of NodeJS # css/css-rwd-frameworks.html "target =" _ blank "> framework express path ing (Routing) function and control, has a certain reference value, for more information, see.

We know that Express is an excellent server development framework based on NodeJS. In this document, CSSer provides the route and route control chapters of the express framework, route implements the path ing function of the URL requested by the client. If you still don't quite understand it, I believe you will get some of it after reading this article.

Routing (URL ing)

Express uses HTTP actions to provide meaningful and expressive URL ing APIs. For example, we may want the user account URL to look like "/user/12, the following example shows how to implement such a route. The value related to the placeholder identifier (id in this example) can be req. params is obtained.

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

In the above example, "user 12" is returned when we access/user/12. CSSer Note: app. get is equivalent to registering a listener to listen to get request events on the server. When the request URL satisfies the first parameter, the callback function is executed. This process is asynchronous.

A route is a simple string that can be internally compiled into a regular expression. For example, when/user/: id is compiled, the internally compiled regular expression string looks like the following (simplified ):

The Code is as follows:

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

To implement the complex point, we can pass in the regular expression to the direct amount, because the regular expression capturing group is anonymous, so we can use req. for params access, the first capture 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 route we have defined:

$ 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 routing examples 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 use the POST method to submit json data, and then use the 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);

Generally, the placeholder (such as/user/: id) We use has no restrictions, that is, users can input IDs of various data types. If we want to restrict the user id to numbers, you can write "/user/: id (\ d +)" in this way to ensure that routing is only performed if the placeholder data type is Numeric.

Route Control

Multiple routes can be defined in an application, and we can control them to switch to the next route. Express provides the third parameter, namely the next () function. When a mode does not match, the control will be switched back to Connect (Express is based on the Connect module), and the middleware will continue to execute in the order they are added in use. This is also true when multiple defined routes may match the same URL, unless a route does not call next () and has output the response to the client, they will also be executed in order.

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

The app. all () method can apply a single call entry to all HTTP actions, which is useful in some cases. Next we will use this function to load a user from our simulated database and allocate 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);

Route parameter preprocessing

Through implicit data processing, the pre-processing of routing parameters can greatly improve the readability of application code and the verification of request URLs. If you frequently obtain general data from several routes, such as loading user information through/user/: id, we may do this:

app.get('/user/:userId', function(req, res, next){ User.get(req.params.userId, function(err, user){  if (err) return next(err);  res.send('user ' + user.name); });});

After preprocessing, parameters can be mapped to callback functions to provide functions such as verification, mandatory value change, and even loading data from the database. Next we will call app. param () and pass in the parameter we want to map to a middleware. We can see that we have received the id parameter containing the placeholder (: userId) value. Here, we can load user data and handle errors as usual, and simply call next () to redirect control to the next preprocessing or routing (path control ).

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(); });});

In this way, not only does the logic implementation mentioned above greatly improve the readability of the route, but also shares the logic implementation of this Part in the entire application for reuse purposes.

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

For simple cases such as route placeholder verification and forced change value, you only need to input one parameter (one parameter is supported). The exception thrown during this period will be automatically passed into next (err ).

app.param('number', function(n){ return parseInt(n, 10); });

You can also apply the callback function to multiple placeholders at the same time. For example, for routing/commits/: from-: to,: from and: to are both numerical values, we can define them as Arrays:

app.param(['from', 'to'], function(n){ return parseInt(n, 10); });

Conclusion

Through the study in this article, we should have some feelings. NodeJS can not only implement the server logic of our products, but also use Javascript For Server programming. Note that it is a server, that is, we can use Javascript to customize functions that can only be done in apache in the past. Does NodeJS still need rewrite? Path ing is simpler and more powerful. What should I do with rewrite?

The above is a detailed description of the node. js framework express's path ing (Routing) function and the sample code for control. For more information, see other related articles in the first PHP community!

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.