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+ 版本中可用)
express.json 中间件的使用
express.json() 中间件,解析表单中的 JSON 格式的数据
案例代码
const express = require('express')
const app = express()
// 注意:除了错误级别的中间件,其他的中间件,必须在路由之前进行配置
// 通过 express.json() 这个中间件,解析表单中的 JSON 格式的数据
app.use(express.json())
app.post('/user', (req, res) => {
// 在服务器,可以使用 req.body 这个属性,来接收客户端发送过来的请求体数据
// 默认情况下,如果不配置解析表单数据中间件,则 req.body 默认等于 undefined
console.log(req.body)
res.send('ok')
})
app.listen(3000, () => {
console.log('running……')
})
express.urlencoded 中间件的使用
express.urlencoded 解析 URL-encoded 格式的请求体数据
案例代码
const express = require('express')
const app = express()
// 通过 express.urlencoded() 这个中间件,来解析表单中的 url-encoded 格式的数据
app.use(express.urlencoded({ extended: false }))
app.post('/book', (req, res) => {
console.log(req.body)
res.send(req.body)
})
app.listen(3000, () => {
console.log('running……')
})
原文:https://www.cnblogs.com/UnfetteredMan/p/13854653.html