1:什么是Express?
- 官方给出的概念:Express 是 基于 Node.js 平台 , 快速、开放、极简 的 Web 开发框架 。
- 通俗的理解:Express 的作用和 Node.js 内置的 http 模块类似, 是专门用来创建 Web 服务器的 。
- Express 的本质 :就是一个 npm 上的第三方包,提供了快速创建 Web 服务器的便捷方法。
2: Express的基本使用
- 安装:
npm i express
- 创建基本的web服务器
const express = require('express')
const app = express()
// 端口启动成功后的回调
app.listen(8084, ()=>{
console.log('8084端口启动成功')
})
- 监听get请求
req: 包含请求相关的属性方法
res: 包含响应相关的属性方法
app.get('/api',function(req,res){
// 处理函数
})
- 监听post请求
req: 包含请求相关的属性方法
res: 包含响应相关的属性方法
app.post('/api',function(req,res){
// 处理函数
})
- 把内容响应给客户端
// 1. 导入 express
const express = require('express')
// 2. 创建 web 服务器
const app = express()
// 4. 监听客户端的 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('请求成功')
})
// 3. 启动 web 服务器
app.listen(80, () => {
console.log('express server running at http://127.0.0.1')
}
- 获取url中携带的query参数
// 1. 导入 express
const express = require('express')
// 2. 创建 web 服务器
const app = express()
app.get('/', (req, res) => {
// 通过 req.query 可以获取到客户端发送过来的 查询参数
// 注意:默认情况下,req.query 是一个空对象
console.log(req.query)
res.send(req.query)
})
// 3. 启动 web 服务器
app.listen(80, () => {
console.log('express server running at http://127.0.0.1')
}
- 获取url中携带的动态params参数
// 1. 导入 express
const express = require('express')
// 2. 创建 web 服务器
const app = express()
// 注意:这里的 :id 是一个动态的参数
app.get('/user/:ids/:username', (req, res) => {
// req.params 是动态匹配到的 URL 参数,默认也是一个空对象
console.log(req.params)
res.send(req.params)
})
// 3. 启动 web 服务器
app.listen(80, () => {
console.log('express server running at http://127.0.0.1')
}
- 托管静态资源
const express = require('express')
const app = express()
// 如果两个文件夹都有index.html文件则先访问的是第一个文件夹里的index.html
app.use(express.static('./clock'))
app.use(express.static('./files'))
// 在这里,调用 express.static() 方法,快速的对外提供静态资源
// 前缀默认与目录一致
app.use('/files', express.static('./files'))
app.use(express.static('./clock'))
app.listen(80, () => {
console.log('express server running at http://127.0.0.1')
})
- nodemon
// 自动启动node插件
npm i nodemon -g
// 使用如下命令启动即可
nodemon app.js
-Express路由
const express = require('express')
const app = express()
// 挂载路由
app.get('/', (req, res) => {
res.send('hello world.')
})
app.post('/', (req, res) => {
res.send('Post Request.')
})
app.listen(80, () => {
console.log('http://127.0.0.1')
})
-模块化路由
- 为了 方便对路由进行模块化的管理 ,Express 不建议 将路由直接挂载到 app 上,而是 推荐将路由抽离为单独的模块 。
- 将路由抽离为单独模块的步骤如下:
- ① 创建路由模块对应的 .js 文件
- ② 调用 express.Router() 函数创建路由对象
- ③ 向路由对象上挂载具体的路由
- ④ 使用 module.exports 向外共享路由对象
- ⑤ 使用 app.use() 函数注册路由模块
// 这是路由模块
// 1. 导入 express
const express = require('express')
// 2. 创建路由对象
const router = express.Router()
// 3. 挂载具体的路由
router.get('/user/list', (req, res) => {
res.send('Get user list.')
})
router.post('/user/add', (req, res) => {
res.send('Add new user.')
})
// 4. 向外导出路由对象
module.exports = router
const express = require('express')
const app = express()
// app.use('/files', express.static('./files'))
// 1. 导入路由模块
const router = require('./03.router')
// 2. 注册路由模块
app.use(router)
// 注意: app.use() 函数的作用,就是来注册全局中间件
app.listen(80, () => {
console.log('http://127.0.0.1')
})
-为路由模块化添加前缀
const express = require('express')
const app = express()
// app.use('/files', express.static('./files'))
// 1. 导入路由模块
const router = require('./03.router')
// 2. 注册路由模块
// app.use(router)
// 添加访问前缀
app.use('/api', router)
// 注意: app.use() 函数的作用,就是来注册全局中间件
app.listen(3030, () => {
console.log('http://127.0.0.1')
})
- Express中间件
Express 的中间件, 本质 上就是一个 function 处理函数
-定义中间件
const express = require('express')
const app = express()
// 定义一个最简单的中间件函数
const mw = function (req, res, next) {
console.log('这是最简单的中间件函数')
// 把流转关系,转交给下一个中间件或路由
next()
}
app.listen(80, () => {
console.log('http://127.0.0.1')
})
全局生效的中间件
const express = require('express')
const app = express()
// 定义一个最简单的中间件函数
const mw = function (req, res, next) {
console.log('这是最简单的中间件函数')
// 把流转关系,转交给下一个中间件或路由
next()
}
// 将 mw 注册为全局生效的中间件
app.use(mw)
app.get('/', (req, res) => {
console.log('调用了 / 这个路由')
res.send('Home page.')
})
app.get('/user', (req, res) => {
console.log('调用了 /user 这个路由')
res.send('User page.')
})
app.listen(80, () => {
console.log('express server running at http://127.0.0.1')
})
-定义全局中间件的简化形式
const express = require('express')
const app = express()
//这是定义全局中间件的简化形式
app.use((req, res, next) => {
console.log('这是最简单的中间件函数')
next()
})
app.get('/', (req, res) => {
console.log('调用了 / 这个路由')
res.send('Home page.')
})
app.get('/user', (req, res) => {
console.log('调用了 /user 这个路由')
res.send('User page.')
})
app.listen(3030, () => {
console.log('express server running at http://127.0.0.1')
})
中间件的作用
多个中间件之间, 共享同一份 req 和 res 。基于这样的特性,我们可以在 上游 的中间件中, 统一 为 req 或 res 对象添加 自定义 的 属性 或 方法 ,供 下游 的中间件或路由进行使用。
const express = require('express')
const app = express()
// 这是定义全局中间件的简化形式
app.use((req, res, next) => {
// 获取到请求到达服务器的时间
const time = Date.now()
// 为 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(80, () => {
console.log('http://127.0.0.1')
})
定义多个全局中间件
const express = require('express')
const app = express()
// 定义第一个全局中间件
app.use((req, res, next) => {
console.log('调用了第1个全局中间件')
next()
})
// 定义第二个全局中间件
app.use((req, res, next) => {
console.log('调用了第2个全局中间件')
next()
})
// 定义一个路由
app.get('/user', (req, res) => {
res.send('User page.')
})
app.listen(80, () => {
console.log('http://127.0.0.1')
})
局部中间件
// 导入 express 模块
const express = require('express')
// 创建 express 的服务器实例
const app = express()
// 1. 定义中间件函数
const mw1 = (req, res, next) => {
console.log('调用了局部生效的中间件')
next()
}
// 2. 创建路由
app.get('/', mw1, (req, res) => {
res.send('Home page.')
})
app.get('/user', (req, res) => {
res.send('User page.')
})
// 调用 app.listen 方法,指定端口号并启动web服务器
app.listen(80, function () {
console.log('Express server running at http://127.0.0.1')
})
多个局部中间件
// 导入 express 模块
const express = require('express')
// 创建 express 的服务器实例
const app = express()
// 1. 定义中间件函数
const mw1 = (req, res, next) => {
console.log('调用了第一个局部生效的中间件')
next()
}
const mw2 = (req, res, next) => {
console.log('调用了第二个局部生效的中间件')
next()
}
// 2. 创建路由
app.get('/', [mw1, mw2], (req, res) => {
res.send('Home page.')
})
// 不会触发中间件
app.get('/user', (req, res) => {
res.send('User page.')
})
// 调用 app.listen 方法,指定端口号并启动web服务器
app.listen(80, function () {
console.log('Express server running at http://127.0.0.1')
})
错误中间件(必须注册再路由之后)
// 导入 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(80, function () {
console.log('Express server running at http://127.0.0.1')
})
Express内置中间件
// 导入 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(80, function () {
console.log('Express server running at http://127.0.0.1')
})
第三方中间件
- 非 Express 官方内置的,而是由第三方开发出来的中间件,叫做第三方中间件。在项目中,大家可以 按需下载 并 配置 第三方中间件,从而提高项目的开发效率。
- 例如:在 express@4.16.0 之前的版本中,经常使用 body-parser 这个第三方中间件,来解析请求体数据。
- 使用步骤如下:
- ① 运行 npm install body-parser 安装中间件
- ② 使用 require 导入中间件
- ③ 调用 app.use() 注册并使用中间件
- 注意: Express 内置的 express.urlencoded 中间件,就是基于 body-parser 这个第三方中间件进一步封装出来的。
// 导入 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(80, function () {
console.log('Express server running at http://127.0.0.1')
})
自定义中间件
- 自己 手动模拟 一个类似于 express.urlencoded 这样的中间件,来 解析 POST 提交到服务器的表单数据 。
- 实现步骤:
- ① 定义中间件
- ② 监听 req 的 data 事件
- ③ 监听 req 的 end 事件
- ④ 使用 querystring 模块解析请求体数据
- ⑤ 将解析出来的数据对象挂载为 req.body
- ⑥ 将自定义中间件封装为模块
// 导入 express 模块
const express = require('express')
// 创建 express 的服务器实例
const app = express()
// 导入 Node.js 内置的 querystring 模块
const qs = require('querystring')
// 这是解析表单数据的中间件
app.use((req, res, next) => {
// 定义中间件具体的业务逻辑
// 1. 定义一个 str 字符串,专门用来存储客户端发送过来的请求体数据
let str = ''
// 2. 监听 req 的 data 事件
req.on('data', (chunk) => {
str += chunk
})
// 3. 监听 req 的 end 事件
req.on('end', () => {
// 在 str 中存放的是完整的请求体数据
// console.log(str)
// TODO: 把字符串格式的请求体数据,解析成对象格式
const body = qs.parse(str)
req.body = body
next()
})
})
app.post('/user', (req, res) => {
res.send(req.body)
})
// 调用 app.listen 方法,指定端口号并启动web服务器
app.listen(80, function () {
console.log('Express server running at http://127.0.0.1')
})
// 导入 Node.js 内置的 querystring 模块
const qs = require('querystring')
const bodyParser = (req, res, next) => {
// 定义中间件具体的业务逻辑
// 1. 定义一个 str 字符串,专门用来存储客户端发送过来的请求体数据
let str = ''
// 2. 监听 req 的 data 事件
req.on('data', (chunk) => {
str += chunk
})
// 3. 监听 req 的 end 事件
req.on('end', () => {
// 在 str 中存放的是完整的请求体数据
// console.log(str)
// TODO: 把字符串格式的请求体数据,解析成对象格式
const body = qs.parse(str)
req.body = body
next()
})
}
module.exports = bodyParser
// 导入 express 模块
const express = require('express')
// 创建 express 的服务器实例
const app = express()
// 1. 导入自己封装的中间件模块
const customBodyParser = require('./14.custom-body-parser')
// 2. 将自定义的中间件函数,注册为全局可用的中间件
app.use(customBodyParser)
app.post('/user', (req, res) => {
res.send(req.body)
})
// 调用 app.listen 方法,指定端口号并启动web服务器
app.listen(80, function () {
console.log('Express server running at http://127.0.0.1')
})
使用Express写接口
const express = require('express')
const router = express.Router()
// 在这里挂载对应的路由
module.exports = router
// 导入 express
const express = require('express')
// 创建服务器实例
const app = express()
// 导入路由模块
const router = require('./16.apiRouter')
// 把路由模块,注册到 app 上
app.use('/api', router)
// 启动服务器
app.listen(80, () => {
console.log('express server running at http://127.0.0.1')
})
const express = require('express')
const router = express.Router()
// 在这里挂载对应的路由
router.get('/get', (req, res) => {
// 通过 req.query 获取客户端通过查询字符串,发送到服务器的数据
const query = req.query
// 调用 res.send() 方法,向客户端响应处理的结果
res.send({
status: 0, // 0 表示处理成功,1 表示处理失败
msg: 'GET 请求成功!', // 状态的描述
data: query, // 需要响应给客户端的数据
})
})
module.exports = router
const express = require('express')
const router = express.Router()
// 定义 POST 接口
router.post('/post', (req, res) => {
// 通过 req.body 获取请求体中包含的 url-encoded 格式的数据
const body = req.body
// 调用 res.send() 方法,向客户端响应结果
res.send({
status: 0,
msg: 'POST 请求成功!',
data: body,
})
})
module.exports = router
// 导入 express
const express = require('express')
// 创建服务器实例
const app = express()
// 配置解析表单数据的中间件
app.use(express.urlencoded({ extended: false }))
// 导入路由模块
const router = require('./16.apiRouter')
// 把路由模块,注册到 app 上
app.use('/api', router)
// 启动服务器
app.listen(80, () => {
console.log('express server running at http://127.0.0.1')
})
CORS跨域
- 刚才编写的 GET 和 POST接口,存在一个很严重的问题: 不支持跨域请求 。
- 解决接口跨域问题的方案主要有两种:
- ① CORS (主流的解决方案, 推荐使用 )
- ② JSONP (有缺陷的解决方案:只支持 GET 请求)
使用 cors 中间件 解决跨域问题
// 导入 express
const express = require('express')
// 创建服务器实例
const app = express()
// 配置解析表单数据的中间件
app.use(express.urlencoded({ extended: false }))
// 一定要在路由之前,配置 cors 这个中间件,从而解决接口跨域的问题
const cors = require('cors')
app.use(cors())
// 导入路由模块
const router = require('./16.apiRouter')
// 把路由模块,注册到 app 上
app.use('/api', router)
// 启动服务器
app.listen(80, () => {
console.log('express server running at http://127.0.0.1')
})
① CORS 主要在 服务器端 进行配置。客户端浏览器 无须做任何额外的配置 ,即可请求开启了 CORS 的接口。
② CORS 在浏览器中 有兼容性 。只有支持 XMLHttpRequest Level2 的浏览器,才能正常访问开启了 CORS 的服务端接口(例如:IE10+、Chrome4+、FireFox3.5+)。
// 设置请求头
// 只循序来自baidu.com的访问请求
res.setHeader('Access-Control-Allow-Origin',"http://baidu.com")
// 任意地址都可以访问
res.setHeader('Access-Control-Allow-Origin',"*")
// 允许客户端向服务器发送Content-Type,X-Cusetom-Header 请求头
res.setHeader('Access-Control-Allow-Headers',"Content-Type,X-Cusetom-Header")
// 只允许POST,GET,DELETE,HADE方法
res.setHeader('Access-Control-Allow-Methods',"POST,GET,DELETE,HADE")
// 只允许所有方法
res.setHeader('Access-Control-Allow-Methods',"*")
预请求
- 只要符合以下任何一个条件的请求,都需要进行预检请求:
- ① 请求方式为 GET、POST、HEAD 之外的请求 Method 类型
- ② 请求头中 包含自定义头部字段
- ③ 向服务器发送 了 application/json 格式的数据
- 在浏览器与服务器正式通信之前,浏览器会 先发送 OPTION 请求进行预检,以获知服务器是否允许该实际请求 ,所以这一 次的 OPTION 请求称为“预检请求”。 服务器成功响应预检请求后,才会发送真正的请求,并且携带真实数据 。