这是我参与「第四届青训营 」笔记创作活动的的第11天
本篇主要讲 express 的一些基础知识。
什么是 express
基于 Node.js 平台,快速、开放、极简的 Web 开发框架。
通俗的来说,就是 原生的 http 内置模块用起来比较复杂,开发效率低。而 express 将原生的 http 模块封装起来,提高我们的开发效率。
基本使用
安装
npm i express
创建基本的web服务器
//1.导入express
const express = require('express')
//2.创建web服务器
const app = express()
//3.调用app.listen(端口号,启动成功的回调函数),启动服务器
app.listen(80,()=>{
console.log('express server running at http://127.0.0.1')
})
监听客服端的GET or POST请求
//参数1:客户端请求的URL地址
//参数2:请求对应的处理函数
// req:请求对象(包含了与请求相关的属性与方法)
// res:响应对象(包含了与响应相关的属性与方法)
app.get('请求URL',function(req,res){
//处理函数
})
实例
//1.导入express
const express = require('express')
//2.创建web服务器
const app = express()
//监听客户端的GET和POST请求,并向客户端响应具体的内容
app.get('/user',(req,res)=>{
//调用express提供的res.send()方法,向客户端下那个音一个JSON对象
res.send({name:'zs',age:20,gender:'男'})
})
app.post('/user',(req,res)=>{
//调用express提供的res.send()方法,向客户端响应一个文本字符串
res.send('请求成功')
})
app.listen(8888,()=>{
console.log('express running at 127.0.0.1:8888');
})
获取URL中携带的查询参数
app.get('/',(req,res)=>{
//req.query 默认是一个空对象
//客户端使用?name=zs&age=20 这种查询字符串形式,发送到服务器的参数
//可以通过req.query对象访问到,例如:
//req.query.name req.query.age
console.log(req.query)
res.send(req.query)
})
获取URL中的动态参数
通过 req.params 对象,可以访问到 URL 中,通过:
匹配到的动态参数
app.get('/:id',(req,res)=>{
//req.params 默认是一个空对象
//里面存放着通过 : 动态匹配的参数值
console.log(req.params);
res.send(req.params);
})
利用express托管静态资源
//如果clock文件夹中包含了index.js,index.html,index.css三个文件
//通过如下的答案可以访问clock下的所有文件
app.use(express.static(./clock))
//访问时就可以直接访问http://127.0.0.1/index.html
//托管多个静态资源目录
app.use(express.static('public'))
app.use(express.static('files'))
//访问静态资源的时候,会从上往下查找文件,如找到了,就不会继续往下查找,直接返回
//挂载路径前缀
app.use('/public',express.static('public'))
//如果挂载了一个访问前缀,那么任何时候访问这个文件都要加上这个前缀
//http://127.0.0.1/piblic/index.html
路由
在 express 中,路由指的是客户端的请求与服务器处理函数之间的映射关系。
路由的匹配过程
每当一个请求到达服务器之后,需要先经过路由的匹配,只有匹配成功之后,才会调用对应的处理函数。
在匹配时,会按照路由的循序进行匹配,如果请求类型和请求的 URL 同时匹配成功,则 Express 会将这次请求转交给对应的 function 函数进行处理。
路由的匹配注意:
1.按照定义的先后顺序进行匹配
2.请求类型和请求的url同时匹配成功,才会调用响应的处理函数
最简单的实例
在 Express 中使用路由最简单的方式,就是把路由挂载到 app 上,实例代码如下:
const express = require('express')
const app = express()
// 挂载路由
app.get('/',(req,res) => { res.send('hello world')})
app.post('/',(req,res) => { res.send('hello world')})
app.listen(80,() => { console.log('server running at http://127.0.0.1')})
模块化路由
注意 为了方便路由进行模块化管理,Express 不建议直接将路由挂载到 app 上,而是推荐将路由抽离为单独的模块。
步骤:
- 创建路由对应的 .js 文件
- 调用 express.Router() 函数创建路由对象
- 向路由对象上挂载具体的路由
- 使用 module.exports 向外共享路由对象 5.使用 app.use() 函数注册路由模块
//Router.js
const express = require("express");
const router = express.Router();
router.get("/user", (req, res) => {
res.send({ name: "zs", age: 20, gender: "男" });
});
router.post("/user", (req, res) => {
res.send("请求成功");
});
router.get("/", (req, res) => {
res.send("server running at / , mothod get");
});
router.post("/", (req, res) => {
res.send("server running at / , mothod post");
});
module.exports = router;
//express.js
const router = require('./router');
const express = require('express')
const app = express()
app.use(router)
app.listen(8888,()=>{
console.log('express running at 127.0.0.1:8888');
})
//如果想加统一的前缀,只需要修改一下
app.use('/api',router)
中间件
中间件的概念:
业务流程的中间处理环节
中间件的调用流程:
当一个请求到达服务器之后,可以连续调用多个中间件,从而对这次请求进行预处理。
中间件的格式
Express 的中间件,本质上就是一个 function 处理函数, Express 中间件的格式如下:
判断一个函数是中间件函数还是路由处理函数,就看它其中是否有 next 参数。路由处理函数中参数只包含 req 和 res。
next函数的作用
next函数是是实现多个中间件调用的关键,他表示吧扭转关系转交给下一个中间件或者路由
定义一个中间件函数
//常量mw所指向的,就是一个中间件函数
const mw = function(req,res,next){
console.log('这是一个简单的中间件函数')
//注意:当中间的业务处理完成之后,必须调用next()函数
//表示将扭转关系转交给下一个中间件或路由
next()
}
定义一个全局生效的中间件
客户端发起的任何请求,到达服务器后,都会触发的中间件,叫全局生效中间件
通过调用 app.use(中间件函数)
,即可定义一个全局生效的中间件
const mw = function(req,res,next){
console.log('这是一个全局生效的中间件')
next()
}
//全局生效的中间件
app.use(mw)
示例
const express = require('express');
const app = express();
const mw = (req,res,next)=>{
console.log('这是一个简单的中间件');
next();
}
app.use(mw);
app.get('/',(req,res)=>{
res.send("server running at / , mothod get");
})
app.get('/user',(req,res)=>{
res.send({name:'zs',age:20,gender:'男'})
})
app.listen(8888,()=>{
console.log('http://127.0.0.1');
})
还可以将中间价这样定义
app.use((req,res,next)=>{
console.log('这是直接用定义在app.use中的中间件');
next();
})
中间件的作用
多个中间件之间,共享同一份 req 和 res,基于这样的特性,我们可以在上游的中间件中,统一为 req 和 res 对象添加自定义的属性或方法,供下游的中间件或路由进行使用。
const express = require("express");
const app = express();
const mw = (req, res, next) => {
const time = Date.now()
req.startTime = time
console.log("这是一个简单的中间件");
next();
};
app.use(mw);
app.get("/", (req, res) => {
res.send("Home Page"+req.startTime);
});
app.get("/user", (req, res) => {
console.log('user Page'+req.startTime)
res.send({ name: "zs", age: 20, gender: "男" });
});
app.listen(8888, () => {
console.log("http://127.0.0.1");
});
上面的 startTime 函数挂载到了 req 身上,那么下游的 中间件和路由 都可以调用 startTime 这个函数。
定义多个全局中间件
可以使用 app.use() 连续定义多个全局中间件,客户端的请求到达服务器之后,会按照中间件定义的先后顺序依次进行调用
const express = require('express');
const app = express();
app.use((req,res,next)=>{
console.log('这是第一个全局中间件');
next();
})
app.use((req,res,next)=>{
console.log('这是第二个全局中间件');
next();
})
app.get('/',(req,res)=>{
res.send("server running at / , mothod get");
})
app.get('/user',(req,res)=>{
res.send({name:'zs',age:20,gender:'男'})
})
app.listen(8888,()=>{
console.log('http://127.0.0.1');
})
局部生效的中间件
const express = require('express');
const app = express();
//定义中间件mw1
const mv1 = (req,res,next)=>{
console.log('调用了局部生效的中间件');
next();
}
//mw1这个中间件只在“当前路由中生效”,这种用法属于“局部生效的中间件”
app.get('/',mv1,(req,res)=>{
res.send("server running at / , mothod get");
})
//mw1这个中间件不会影响下面这个路由
app.get('/user',(req,res)=>{
res.send({name:'zs',age:20,gender:'男'})
})
app.listen(8888,()=>{
console.log('http://127.0.0.1');
})
可以在路由中,定义多个局部生效的中间件,下面两种方法完全一致。
app.get('/',mw1,mw2,(req,res)=>{
res.send('Home Page')
})
app.get('/',[mw1,mw2],(req,res)=>{
res.send('Home Page')
})
中间件的注意事项
- 一定要在路由之前注册中间件
- 客户端发送过来的请求,可以连续调用多个中间件进行处理
- 执行完中间件的业务代码之后,不要忘记调用next()函数
- 为了防止代码的逻辑混乱,调用了next()函数后不要在写额外的代码
- 连续调用多个中间件时,多个中间件之间,共享req和res
中间件的分类
应用级别的中间件
通过app.use或app.ger()或app.post(), 绑定到app实例上的中间件
,叫做应用级别的中间件。
路由级别的中间件
绑定到express.Router()实例上的中间件,它的用法和饮用级别中间件没有任何区别,只不过,应用级别的中间件时绑定到 app 实例上,路由级别的中间件绑定到 router 实例上。
- 错误级别的中间件
专门用来捕获整个项目中发生的一场错误,以防项目出现异常崩溃的现象
格式:错误级别的中间件的 function 处理函数中,必须有四个参数,参数顺序从前往后,分别是 (err,req,res,next)
app.get("/", (req, res) => {
throw new Error('服务器发生了错误!');
res.send("Home Page");
});
app.use(function(err,req,res,next){
console.log('发生了错误'+err.message)
res.send('Error '+err.message)
})
错误级别的中间件,必须注册在所有路由之后。
express内置的中间件、
Express 内置了3个常用的中间件,极大的提高了 Express 的开发效率。
//1.express.static快速托管静态资源的内置中间件,例如:HTML文件,图片,css样式等
//2.express.json解析JSON格式的请求数据
app.use(express.json())
//3.express.urlencoded解析URL-encoded格式的请求体数据
app.use(express.urlencoded({ extended:false }))
实例(express.json)
const express = require('express');
const app = express();
app.use(express.json());
app.get('/',function(req,res){
//在服务器中,可以使用 req.body 这个属性,来接收客户端发送过来的请求体数据
//默认情况下,如果不配置解析表单数据的中间件,则 req.body 默认等于 undefined
console.log(req.body);
res.send('Home Page');
})
app.listen(8888,()=>{
console.log('http://127.0.0.1');
})
实例(urlencoded)
const express = require('express');
const app = express();
app.use(express.urlencoded({ extended:false }));
app.get('/',function(req,res){
//在服务器中,可以使用 req.body 这个属性,来接收客户端发送过来的请求体数据
//默认情况下,如果不配置解析表单数据的中间件,则 req.body 默认等于 undefined
console.log(req.body);
res.send('Home Page');
})
app.listen(8888,()=>{
console.log('http://127.0.0.1');
})
第三方中间件
非 Express 官方内置的,而是由第三方开发出来的中间件,叫做第三方中间件。在项目中,大家可以按需下载并配置第三方中间件,从而提高项目的开发效率。
const express = require('express');
const parser = require('body-parser');
const app = express();
app.use(parser.urlencoded({extended:false }));
app.get('/',function(req,res){
//在服务器中,可以使用 req.body 这个属性,来接收客户端发送过来的请求体数据
//默认情况下,如果不配置解析表单数据的中间件,则 req.body 默认等于 undefined
console.log(req.body);
res.send('Home Page');
})
app.listen(8888,()=>{
console.log('http://127.0.0.1');
})
自定义中间件
const express = require('express')
const qs = require('querystring')
const app = express()
// 这是解析表单数据的中间件
const mw = function(req,res,next){
let str = ''
req.on('data',(chunk)=>{
str+=chunk
})
req.on('end',()=>{
const body = qs.parse(str)
req.body = body
next()
})
}
app.use(mw)
app.post('/user',(req,res)=>{
res.send(req.body)
})
app.listen(8888,() => { console.log('server running at http://127.0.0.1')})
更加详细的细节,请参考这篇文章:blog.csdn.net/weixin_4599…
结语
文章如果有不正确的地方,欢迎指正,共同学习,共同进步。
若有侵权,请联系作者删除。