走进Node.js
前言
万字长文 值得收藏
本篇文章记录的是Node.js 关于Express的有关内容
如果文章有什么需要改进的地方还请大佬不吝赐教👏👏
在此先感谢各位大佬啦~~🤞🤞
一、Express
1.Express的定义
Express 是基于 Node.js 平台,快速、开放、极简的 Web 开发框架。
2.Express的作用
使用 Express,我们可以方便、快速的创建 Web 网站的服务器或 API 接口的服务器。
3.Express的基本使用
①安装express
npm install express@版本号
或
npm i express@版本号 //版本号可省略
②用express创建基本web服务器
流程:
- 导入express模块
- 创建web服务器
- 调用app.listen()函数启动服务器
代码示例:
// 1.导入express模块
const express = require('express')
// 2.创建web服务器
const app = express()
// 3.调用app.listen()函数启动服务器
app.listen(4040,()=>{ // 4040为端口号
console.log('server running at http://127.0.0.1:4040') //打印服务器状态
})
③监听 GET 和 POST 请求
代码示例:
app.get('请求url',(req,res)=>{
})
app.post('请求url',(req,res)=>{
})
④获取url中携带的参数
通过 req.query
对象可以访问到 客户端查询字符串的形式
发送到服务器的参数,默认是一个空对象
代码示例:
app.get('/user', (req, res) => {
console.log(req.query)
res.send(req.query)
})
⑤获取url中的动态参数
通过req.params
对象可以访问url中通过匹配到的动态参数
代码示例:
app.get('/:id', (req, res) => {
console.log(req.params)
res.send(req.params)
})
⑥req.body
- 在服务器,可以使用
req.body
这个属性,来接收客户端发送过来的请求体数据 - 默认情况下,如果
不配置解析表单数据的中间件
,则 req.body 默认等于 undefined
代码示例:
// 导入 express 模块
const express = require('express')
// 创建 express 的服务器实例
const app = express()
// 注意:除了错误级别的中间件,其他的中间件,必须在路由之前进行配置
// 通过 express.json() 这个中间件,解析表单中的 JSON 格式的数据
app.use(express.json())
// 通过 express.urlencoded() 这个中间件,来解析 表单中的 url-encoded 格式的数据
app.use(express.urlencoded({ extended: false }))
app.post('/user', (req, res) => {
// 在服务器,可以使用 req.body 这个属性,来接收客户端发送过来的请求体数据
// 默认情况下,如果不配置解析表单数据的中间件,则 req.body 默认等于 undefined
console.log(req.body)
res.send('ok')
})
app.post('/book', (req, res) => {
// 在服务器端,可以通过 req,body 来获取 JSON 格式的表单数据和 url-encoded 格式的数据
console.log(req.body)
res.send('ok')
})
// 调用 app.listen 方法,指定端口号并启动web服务器
app.listen(4040, function () {
console.log('Express server running at http://127.0.0.1:4040')
})
4.Express路由
介绍:
- 在
Express
中,路由指的是客户端的请求与服务器处理函数之间的映射关系 - Express 中的路由分 3 部分组成,分别是请求的类型、请求的 URL 地址、处理函数
①模块化路由
流程:
- 创建路由对应的js文件 router.js 和 test.js
- 调用express.Router()函数创建路由对象
- 向路由对象上挂载具体的路由
- 使用module.exports向外共享路由对象
- 使用app.use()函数注册路由模块
代码示例:
router.js部分
//1.导入express模块
const express = require('express')
//2.调用express.Router()函数创建路由对象
const router = express.Router()
//3.向路由对象上挂载具体的路由
router.get('/user/get', (req, res) => {
res.send('GET success')
})
router.post('/user/post', (req, res) => {
res.send('POST success')
})
//4.使用module.exports向外共享路由对象
module.exports = router
test.js部分
//1.导入express模块
const express = require('express')
const app = express()
//2.引入路由模块并使用app.use()函数注册路由模块
const router = require('./router')
app.use('/api', router)
app.listen(4040, () => {
console.log('server running at http://127.0.0.1:4040')
})
5.Express中间件
Express 的中间件,本质上就是一个 function 处理函数
代码示例:
function (req,res,next){
next()
}
注意:
- 中间件函数的形参列表中,必须包含 next 参数。而路由处理函数中只包含 req 和 res
- next 函数是实现多个中间件连续调用的关键,它表示把流转关系转交给下一个中间件或路由
①定义中间件
代码示例:
const nw=(req,res,next)=>{
next()
}
②全局生效的中间件
- 客户端发起的任何请求,到达服务器后都会先触发中间件
- 通过app.use(中间件函数) 定义一个全局生效的中间件
代码示例:
//单个全局生效的中间件
const nw=(req,res,next)=>{
next()
}
app.use(nw)
//简化形式
app.use((req,res,next)=>{
next()
})
//多个全局生效的中间件
app.use((req,res,next)=>{
console.log('第一个中间件')
next()
})
app.use((req,res,next)=>{
console.log('第二个中间件')
next()
})
//会按照定义中间件的顺序来执行
③中间件的作用
- 多个中间件之间,共享同一份 req 和 res,基于这样的特性,我们可以在上游 的中间件中,统一为 req 或 res 对象添加自定义的属性和方法,供下游的中间件或路由进行使用。
代码示例:
const express = require('express')
const app = express()
// 这是定义全局中间件的简化形式
app.use((req, res, next) => {
// 获取到请求到达服务器的时间
// const time = Date.now()
var time = new Date()
// 为 req 对象,挂载自定义属性,从而把时间共享给后面的所有路由
req.startTime = time
next()
})
app.get('/', (req, res) => {
res.send('Home page.' + req.startTime)
})
app.get('/user', (req, res) => {
res.send('User page.' + req.startTime)
})
app.listen(4040, () => {
console.log('http://127.0.0.1:4040')
})
④局部生效的中间件
注意:不适应app.use()定义的中间件
//单个局部中间件
const nw=(req,res,next)=>{
next()
}
app.get('/',nw,(req,res)=>{
})
//多个局部中间件
const nw=(req,res,next)=>{
next()
}
const nw1=(req,res,next)=>{
next()
}
app.get('/',[nw,nw1],(req,res)=>{
})
⑤使用中间件的注意事项
- 一定要在路由之前注册中间件
- 客户端发送过来的请求,可以连续调用多个中间件进行处理
- 执行完中间件的业务代码之后,不要忘记调用 next() 函数
- 为了防止代码逻辑混乱,调用 next() 函数后不要再写额外的代码
- 连续调用多个中间件时,多个中间件之间,共享 req 和 res 对象
6.中间件的分类
①应用级别的中间件
通过 app.use() 或 app.get() 或 app.post() ,绑定到 app 实例上的中间件,叫做应用级别的中间件
代码示例:
app.get('/api', (req, res) => {
res.send('get 请求成功')
})
app.post('/api', (req, res) => {
res.send('post 成功')
})
②路由级别的中间件
- 绑定到 express.Router() 实例上的中间件,叫做路由级别的中间件
- 用法上和应用级别中间件没有任何区别,只不过,应用级别中间件是绑定到 app 实例上,路由级别中间件绑定到 router 实例上
代码示例:
const express = require('express')
const app = express()
const router = express.Router()
router.use((req,res,next)=>{
next()
})
app.use('/api', router);
app.listen(4040, () => {
console.log('http://127.0.0.1:4040')
})
③错误级别的中间件
- 错误级别中间件的作用: 专门用来捕获整个项目中发生的异常错误,从而防止项目异常崩溃的问题
- 格式:错误级别中间件的 function 处理函数中,必须有 4 个形参,形参顺序从前到后,分别是 (err, req, res, next)
注意:
错误级别的中间件,必须注册在所有路由之后
代码示例:
// 导入 express 模块
const express = require('express')
// 创建 express 的服务器实例
const app = express()
// 1. 定义路由
app.get('/', (req, res) => {
// 1.1 人为的制造错误
throw new Error('服务器内部发生了错误!')
res.send('Home page.')
})
// 2. 定义错误级别的中间件,捕获整个项目的异常错误,从而防止程序的崩溃
app.use((err, req, res, next) => {
console.log('发生了错误!' + err.message)
res.send('Error:' + err.message)
})
// 调用 app.listen 方法,指定端口号并启动web服务器
app.listen(4040, function () {
console.log('Express server running at http://127.0.0.1:4040')
})
④内置级别的中间件
express.static
快速托管静态资源的内置中间件express.json
解析JSON
格式的请求体数据express.urlencoded
解析URL-encoded
格式的请求体数据
代码示例:
const express = require('express')
const app = express()
//express.json() 中间件,解析表单中的 JSON 格式的数据
app.use(express.json())
//express.urlencoded 解析 URL-encoded 格式的请求体数据
app.use(express.urlencoded({ extended: false }))
app.post('/api', (req, res) => {
console.log(req.body)
res.send('post 成功')
})
app.listen(4040, () => {
console.log('running at http://127.0.0.1:4040')
})
⑤第三方的中间件
- 非
Express
官方内置,而是由第三方开发出来的中间件,叫做第三方中间件。在项目中,大家可以按需下载并配置第三方中间件,从而提高项目的开发效率 - 在
express@4.16.0
之前的版本中,经常使用body-parser
这个第三方中间件,来解析请求体数据 - 使用步骤:
- 运行
npm install body-parser
安装中间件 - 使用
require
导入中间件 - 调用
app.use()
注册并使用中间件
- 运行
代码示例:
// 导入 express 模块
const express = require('express')
// 创建 express 的服务器实例
const app = express()
// 1. 导入解析表单数据的中间件 body-parser
const parser = require('body-parser')
// 2. 使用 app.use() 注册中间件
app.use(parser.urlencoded({ extended: false }))
// app.use(express.urlencoded({ extended: false }))
app.post('/user', (req, res) => {
// 如果没有配置任何解析表单数据的中间件,则 req.body 默认等于 undefined
console.log(req.body)
res.send('ok')
})
// 调用 app.listen 方法,指定端口号并启动web服务器
app.listen(4040, function () {
console.log('Express server running at http://127.0.0.1:4040')
})
注意:Express 内置的 express.urlencoded 中间件,就是基于 body-parser 这个第三方中间件进一步封装出来的
二、使用express写接口
1.创建web服务器
// 导入 express 模块
const express = require('express')
// 创建 express 的服务器实例
const app = express()
//设置解析数据
app.use(express.urlencoded({ extended: false }))
// 导入路由模块
const router = require('./16.apiRouter')
// 把路由模块,注册到 app 上
app.use('/api', router)
// 调用 app.listen 方法,指定端口号并启动web服务器
app.listen(4040, function () {
console.log('Express server running at http://127.0.0.1:4040')
})
2.创建API路由模块
const express = require('express')
const router = express.Router()
//get请求
router.get('/get', (req, res) => {
var query = req.query
res.send({
status: 0,
msg: "GET 请求成功",
data: query
});
});
//post请求
router.post('/post', (req, res) => {
var body = req.body
res.send({
status: 0,
msg: "POST请求成功",
data: body
})
})
module.exports = router
小结
以上就是Node.js 关于 express 的相关内容,后续将会围绕Node.js的相关内容及其知识点不定期持续更新,感谢一路有你们的关注和陪伴!(若有错误,请批评改正,谢谢~)