search
HomeWeb Front-endJS TutorialDetailed 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.json

In 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

error handling can be carried out as usual, and control can be transferred to the next preprocessing or routing (path control) simply 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();

 });

});

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software