Express初始化
初始化
npm init
npm i express
基础代码
const express = require('express')
const app = express()
const port = 3000
app.use((req, res, next) => {
console.log('收到请求:', req.method, req.url)
next()
})
app.get('/users/:userId/books/:bookId', (req, res) => {
console.log('匹配到了路由!')
res.json(req.params)
})
app.listen(port, () => {
console.log(`服务器已启动`)
})
Middleware
这段代码是 Express 中最核心的概念之一——中间件(Middleware)。
app.use((req, res, next) => {
console.log('收到请求:', req.method, req.url)
next()
})
"每次有请求进来,先打印日志,然后放行让后面的代码继续处理"
用生活场景理解
假设你是一个快递站:
- 快递员(请求) 送来一个包裹
- 你(中间件) 先登记包裹信息(打印日志):"收到来自张三的包裹"
- 然后你递给下一个工作人员(
next()) 去处理 - 下一个工作人员可能是分拣员(下一个中间件) ,也可能是送货员(最终路由)
如果没有 next(),包裹就卡在你手里,永远不会送到客户手上。
间件的常见用途
| 用途 | 示例 |
|---|---|
| 日志记录 | 打印请求信息 |
| 身份验证 | 检查用户是否登录,没登录就拦截 |
| 解析请求体 | express.json() 解析JSON数据 |
| CORS跨域 | 允许跨域请求 |
| 静态文件 | express.static() 托管静态资源 |
| 压缩响应 | compression() 压缩返回数据 |
nodemon
想让修改代码后服务器自动重启,你需要使用 nodemon 这个工具。 方式一:
npm install --save-dev nodemon
nodemon app.js
方式二:
如果你用的是 Node.js 18.11.0 或更高版本,不需要安装任何东西:
node --watch app.js
路由(Routes)
RESTful API 路由设计
// 同一个路径,不同方法
app.get('/users', (req, res) => {}) // 查询所有用户
app.post('/users', (req, res) => {}) // 创建用户
app.put('/users/:id', (req, res) => {}) // 更新用户
app.delete('/users/:id', (req, res) => {}) // 删除用户
路由链式调用
app.route('/users/:id')
.get((req, res) => { /* 查询 */ })
.put((req, res) => { /* 更新 */ })
.delete((req, res) => { /* 删除 */ })
请求
## 请求对象
app.get('/example/:id', (req, res) => {
req.params // 路径参数: { id: '123' }
req.query // 查询参数: ?name=John&age=18 -> { name: 'John', age: '18' }
req.body // 请求体: POST/PUT 提交的数据(需要中间件解析)
req.headers // 请求头: { 'content-type': 'application/json', ... }
req.cookies // Cookie 数据(需要 cookie-parser)
req.ip // 客户端 IP
req.path // 请求路径: /example/123
req.method // 请求方法: GET/POST/PUT/DELETE
req.hostname // 主机名: localhost
})
解析请求体
// 必须加这两个中间件,否则 req.body 是 undefined
app.use(express.json()) // 解析 JSON 格式的 body
app.use(express.urlencoded({ extended: true })) // 解析表单格式的 body
app.post('/users', (req, res) => {
console.log(req.body.name) // 现在能取到了
})