Home > Article > Web Front-end > Detailed explanation of the path mapping (routing) function and control sample code of the NodeJS framework express
This article mainly introduces the detailed explanation of NodeJS The path mapping (routing) function and control of the framework express has certain reference value. Interested friends can refer to it
We know that Express is based on NodeJS. A very excellent server-side development framework, this CSSer will provide the route and route control chapters of the express framework. Route implements the path mapping function of the URL requested by the client. Let’s translate it as routing or URL mapping if you are still not sure. Understand, I believe you will gain something after reading this article
Routing (URL mapping)
Express uses HTTP actions to provide meaningful and expressive functions. URL mappingAPI, for example, we may want the URL of the user account to look like "/user/12". The following example can achieve such routing, with the placeholder identifier (in this example is: id) The related value can be obtained by req.params
app.get('/user/:id', function(req, res){ res.send('user ' + req.params.id); });
In the above example, when we access /user/12, "user 12" is returned. CSSer Note: app.get is equivalent to registering on the server. A listener is created to listen to the get request event. When the requested URL meets the first parameter, the following callback function is executed. The process is asynchronous.
Routing is a can. A simple string that is internally compiled into a regular expression. For example, when /user/:id is compiled, the internally compiled regular expression string will look like the following It looks like (after simplification):
The code is as follows:
\/user\/([^\/]+)\/?
To achieve something more complex, we can pass in the regular expression literal, because the regular capture group is anonymous, so we can pass req.params to 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); });
Through Linux##. #The curl command to test the routes we 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"]The following 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.jsonIn addition, we can submit json data through POST , 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);Usually there are no restrictions on the placeholders we use (such as /user/:id), that is, users can Pass in id values of various
data types. If we want to limit the user id to a number, we can write "/user/:id(\d+)" like this to ensure that there is only that placeholder. Only when the character data type is numeric type will routing related processing be performed.
Routing control
An application can define multiple routes, and we can control it to move to the next route. Express provides the third parameter, next( )function. When a pattern is not matched, control will be transferred back to Connect (Express is based on the Connect module), and middleware will continue to be executed in the order in which they were added in use(). This is also true when multiple defined routes may all 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) { // 一回注:如果在这里就将响应内容输出给客户端,那么后续的URL映射将不会被调用 } else { next(); // 将控制转向下一个符合URL的路由 } }); 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. Below we use this function to load a user from our mock 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 parametersPreprocessing
Routing parameter preprocessing can greatly improve the readability and readability of application code through implicit data processing. Validation of request URL. If you frequently obtain common data from several routes, such as loading user information through /user/:id, usually 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, the parameters can be mapped to the callback function, This allows you to provide functionality such as validation, forcing changes to values, and even loading data from a database. Next we will call app.param() and pass in the parameter we want to map to a certain middleware. You can see that we receive the id parameter containing the placeholder (:userId) value. Here, user data loading and
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 doing so, it can not only greatly improve the readability of routing as mentioned above, but also share the logic implementation of this part throughout the application to achieve reuse.
app.get('/user/:userId', function(req, res){ res.send('CSSer用户为 ' + req.user.name); });For simple situations such as route placeholder verification and forced value change, only one parameter needs to be passed in (one parameter is supported), and the exception thrown during the period will be automatically passed to next(err).
app.param('number', function(n){ return parseInt(n, 10); });
也可以同时将回调函数应用到多个占位符,比如路由/commits/:from-:to来说,:from和:to都是数值类型,我们可以将它们定义为数组:
app.param(['from', 'to'], function(n){ return parseInt(n, 10); });
结语
通 过本文的学习,我们应该有些感觉了,NodeJS不仅仅可以实现我们产品的服务端逻辑,同时我们还可以利用Javascript做服务器编程,注意是服务 器,也就是说,我们可以利用Javascript来定制以往只能在apache中才可以做到的功能。NodeJS还需要rewrite吗?路径映射更简单 更强大,还要rewrite干嘛用?
The above is the detailed content of Detailed explanation of the path mapping (routing) function and control sample code of the NodeJS framework express. For more information, please follow other related articles on the PHP Chinese website!