search
HomeWeb Front-endJS TutorialAn in-depth analysis of express routing in node.js

This article will take you through the express routing in node and introduce the basic usage. I hope it will be helpful to everyone!

An in-depth analysis of express routing in node.js

1. The concept of routing

##1.1 What is routing

Broadly speaking, routing is

mapping relationship.

In real life

##

按键 1  ->  业务查询
按键 2  ->  手机充值
按键 3  ->  业务办理
按键 4  ->  密码服务与停复机
按键 5  ->  家庭宽带
按键 6  ->  话费流量
按键 8  ->  集团业务
按键 0  ->  人工服务

在这里,路由是按键与服务之间的映射关系
An in-depth analysis of express routing in node.js

1.2 Routing in nodejs## The routing in #nodejs

is actually the mapping relationship between the url address and the response function. A url address responds to an html page.

It is to extract the business of a path matching relationship into a separate js file.

2. Express

2.1 Introduction to Express

Based on the Node.js platform, a fast, open and minimalist web development framework

express official website (http ://expressjs.com/)
    express Chinese website (http://expressjs.com.cn/)
  • 1. The role of Express and Node.js The built-in http module is similar and is specifically used to create web servers.
2. The essence of Express: It is a third-party package on npm that provides a convenient way to quickly create a web server.


Learn more about express

Thinking: Can I create a web server without using Express?

Answer: Yes, just use the native http module provided by Node.js.

Thinking: If you are already good, why should you be bright (with the http built-in module, why do you still use Express)?
Answer: The built-in http module is very complicated to use and the development efficiency is low; Express is further encapsulated based on the built-in http module, which can greatly improve development efficiency.

Thinking: What is the relationship between the http built-in module and Express?
Answer: Similar to the relationship between Web API and jQuery in the browser. The latter is further encapsulated based on the former.


2.2 Basic steps

##Installation: npm i express

  • // 导入 express
    var express = require('express');
    // 创建 express实例,也就是创建 express服务器
    var app = express();
    
    
    // 启动服务器
    app.listen(3000, function () {
      console.log('服务器已启动')
    })
    Monitoring get requests

Through the app.get() method, you can monitor the client's GET requests. The specific syntax format is as follows:

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-wu5WkyIV-1639963661922)(images3/image-2020052923160665An in-depth analysis of express routing in node.js)]

Listen to post requests

Through the app.post() method, you can monitor the client's POST request. The specific syntax format is as follows:

[External link The image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img-wzB8FFER-1639963661923)(images3/image-20200529231710830.png)]

Response content to the customer The client

can send the processed content to the client through the res.send() method: [External link image transfer failed, the source site may have anti-leeching mechanism, it is recommended to save the image and upload it directly (img-Iiifw7XV-1639963661924)(images3/image-20200529231837638.png)]

2.3 Detailed explanation of req attribute

Get the parameters of the get request

Through the req.query object, you can get the parameters sent by the client to the server through GET: For example: http://127.0.0.1:3000/index?id=10&name=tom&age=20

[The external link image transfer failed. The source site may have an anti-leeching mechanism. It is recommended to save the image and upload it directly (img -WUoF7b2h-1639963661925)(images3/image-20200529231928577.png)]

##Name

Functionreq.queryGet the parameters passed by the Get request and get an objectreq.body Get the data passed by the Post request. What you get is an object. You need to register a middleware.req.paramsGet the routing parameters in the Get request and get is an objectExample: jd.com/32342545365app.get('/product/:id')Get the Value corresponding to the specified Key in the request header

获取post请求的参数

通过req.body可以获取post请求的参数,但是需要配合body-parser中间件

不再需要使用req.on(‘data’,chunk=>{})         req.on(‘end’,()=>{})

如果没有这个中间件的话,则默认获取的是undefined.

// 最新的express版本,不再需要body-parse的下载支持了,直接按如下的方式来书写即可 
app.use(express.urlencoded({ extended: true }))
app.post('/index',(req,res)=>{
  console.log(req.body);
})

2.4 res属性详解

// send() 发送数据给客户端,并自动设置Content-Type
res.send()  //用于向浏览器客户端响应数据 会自带合适的响应头

// 发送文件给浏览器,并根据文件后缀名自动设置Content-Type
// 注意:文件路径必须是绝对路径
res.sendFile(path.join(__dirname, 'index.html'))

// 设置响应头
res.set('Content-Type', 'text/plain')
res.set({
  'Content-Type': 'text/plain',
  'cute': 'fangfang'
})

// 重定向 
res.redirect('/index')

req.get(key)
方法 作用
res.send() 响应给客户端浏览器的数据,会自带响应头
send方法在将上面的对象数据响应给浏览器的时候,相当于内部会调用 JSON.stringify()
res.sendFile(path) 响应给浏览器一个页面
res.redirect() 重定向 会自带状态码
res.set(key,value) 自定义响应头
res.status() 设置响应状态码

2.5 express路由处理

基本使用

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-D3rId34r-1639963661925)(images3/image-20200529233016669.png)]

  • app.get(path, callback)
  • app.post(path, callback)
  • app.use(path, callback) 更重要的作用是处理中间件
    • 注意:只要是以path开头的请求地址,都可以被use处理
    • 注意:可以处理任意的请求类型
    • 注意:path参数可省略,默认值为:/
// all可以匹配任何提交方式 get和post都可以
app.all('*',(req,res)=>{
 // 做一个其它比较友好界面 响应给浏览器
  res.send('页面还没完成,请等待...')
})

路由的匹配过程

每当一个请求到达服务器之后,需要先经过路由的匹配,只有匹配成功之后,才会调用对应的处理函数。

在匹配时,会按照路由的顺序进行匹配,如果请求类型和请求的 URL 同时匹配成功,则 Express 会将这次请求,转交给对应的 function 函数进行处理。

An in-depth analysis of express routing in node.js

路由匹配的注意点:

①按照定义的先后顺序进行匹配

②请求类型和请求的URL同时匹配成功,才会调用对应的处理函数

全局挂载路由

在 Express 中使用路由最简单的方式,就是把路由挂载到 app 上,示例代码如下

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pdjsILgz-1639963661927)(images3/image-2020052923325460An in-depth analysis of express routing in node.js)]

2.6 模块化路由

        为了方便对路由进行模块化的管理,Express 不建议将路由直接挂载到 app 上,而是推荐将路由抽离为单独的模块。

将路由抽离为单独模块的步骤如下:

①创建路由模块对应的 .js 文件 router.js

②调用 express.Router() 函数创建路由对象

③向路由对象上挂载具体的路由

④使用 module.exports 向外共享路由对象

⑤使用 app.use() 函数注册路由模块

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3fEDx0H3-1639963661928)(images3/image-2020052923332450An in-depth analysis of express routing in node.js)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QAUKjV4x-1639963661931)(images3/image-20200529233330060.png)]

2.7 静态资源处理

基本使用

express 提供了一个非常好用的函数,叫做 express.static(),通过它,我们可以非常方便地创建一个静态资源服务器,例如,通过如下代码就可以将 public 目录下的图片CSS 文件、**JavaScript **文件对外开放访问了:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-C1BTBqzr-1639963661933)(images3/image-2020052923240715An in-depth analysis of express routing in node.js)]

现在,你就可以访问 public 目录中的所有文件了:
http://localhost:3000/images/bg.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/login.js

注意:Express 在指定的静态目录中查找文件,并对外提供资源的访问路径。
因此,存放静态文件的目录名不会出现在 URL 中。

托管多个资源目录

如果要托管多个静态资源目录,请多次调用 express.static() 函数:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Px6ZUuaQ-1639963661934)(images3/image-20200529232555610.png)]

上面的设置需要注意的是:在html页面中的那些静态资源路径一定不要在出现public

访问静态资源文件时,express.static() 函数会根据目录的添加顺序查找所需的文件。

挂载路径前缀

如果希望在托管的静态资源访问路径之前,挂载路径前缀,则可以使用如下的方式:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-e13liOYs-1639963661934)(images3/image-2020052923262669An in-depth analysis of express routing in node.js)]

现在,你就可以通过带有 /public 前缀地址来访问 public 目录中的文件了:
http://localhost:3000/public/images/kitten.jpg
http://localhost:3000/public/css/style.css
http://localhost:3000/public/js/app.js

2.8 express中间件

什么是中间件

中间件(Middleware )其实就是一个函数,特指业务流程的中间处理环节。

分为全局中间件和路由中间件。

中间件分为两种 一个是全局中间件 一个是路由中间件

现实生活中的例子

An in-depth analysis of express routing in node.js

处理污水的这中间处理环节,就可以叫做中间件。

express中的中间件

当一个请求到达 Express 的服务器之后,可以连续调用多个中间件,从而对这次请求进行预处理。

An in-depth analysis of express routing in node.js

基本使用

Express 的中间件,本质上就是一个 function 处理函数,Express 中间件的格式如下:

const mw = function(req, res, next) {
  next()
}
app.use(mw)

注意:中间件函数的形参列表中,必须包含 next 参数。而路由处理函数中只包含 req 和 res。

next函数的作用: next 函数是实现多个中间件连续调用的关键,它表示把流转关系转交给下一个中间件或路由。

An in-depth analysis of express routing in node.js

中间件的作用

多个中间件之间,共享同一份 req res。基于这样的特性,我们可以在上游的中间件中,统一为 req 或 res 对象添加自定义的属性或方法,供下游的中间件或路由进行使用。

An in-depth analysis of express routing in node.js

定义多个中间件

可以使用 app.use() 连续定义多个全局中间件。客户端请求到达服务器之后,会按照中间件定义的先后顺序依次进行调用,示例代码如下:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-s5pYXD4F-1639963661937)(images3/image-2020052923390169An in-depth analysis of express routing in node.js)]

express内置中间件

自 Express 4.16.0 版本开始,Express 内置了 3 个常用的中间件,极大的提高了 Express 项目的开发效率和体验:

① express.static 快速托管静态资源的内置中间件,例如: HTML 文件、图片、CSS 样式等(无兼容性)

② express.json 解析 JSON 格式的请求体数据(有兼容性,仅在 4.16.0+ 版本中可用)

③ express.urlencoded 解析 URL-encoded 格式的请求体数据(有兼容性,仅在 4.16.0+ 版本中可用)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-WJaSINca-1639963661937)(images3/image-20200529234155137.png)]

3.EJS模板

3.1 ejs介绍

ejs是一个高效的javascript模板引擎,是为了使用户页面与业务数据(分离)而产生的。

简单来说,使用ejs模板引擎就可以帮助我们快速的将数据渲染到页面对应的位置,和art-template模板类似.

3.2 ejs的使用

1.下载

npm i ejs

2.配置模板引擎

app.set('view engine','ejs')

3.配置模板的存放目录

app.set('views','./views')   //默认的是可以省略

4.在views目录下创建模板文件    views文件夹中的静态页面此时应该修改后缀.ejs

5.使用模板渲染数据

res.render('index',obj)
//第一个参数就是要渲染的页面,直接写名称不用加后缀
//第二个参数表示待渲染的对象,通常是一个对象

3.3 数据渲染

     写业务逻辑

   在某位置输出数据

    不转义输出

更多node相关知识,请访问:nodejs 教程!!

The above is the detailed content of An in-depth analysis of express routing in node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
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.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor