一、前置环境准备
1. 安装 Node.js
Express 依赖 Node.js,先安装:
-
推荐版本:LTS 长期稳定版
-
验证安装:
node -v # 查看 Node 版本
npm -v # 查看 npm 版本
2. 初始化项目
创建项目文件夹并初始化:
# 1. 创建文件夹并进入
mkdir express-demo && cd express-demo
# 2. 初始化 package.json(一路回车即可)
npm init -y
3. 安装 Express
npm install express
二、快速入门:第一个 Express 服务
1. 最简服务器代码
创建 app.js(项目入口文件):
// 1. 引入 express
const express = require('express')
// 2. 创建应用实例
const app = express()
// 3. 定义端口
const PORT = 3000
// 4. 编写接口/路由
// 根路由 GET 请求
app.get('/', (req, res) => {
res.send('Hello Express! 我的第一个服务')
})
// 5. 启动服务
app.listen(PORT, () => {
console.log(`服务已启动:http://localhost:${PORT}`)
})
2. 启动服务
node app.js
打开浏览器访问:http://localhost:3000,即可看到返回内容。
三、核心基础:路由与请求方法
路由是请求方法 + 请求路径 + 处理函数,是 Express 最核心功能。
1. 常用 HTTP 请求方法
// GET:获取数据(查询)
app.get('/api/user', (req, res) => {
res.send({ name: '张三', age: 20 })
})
// POST:新增数据(提交)
app.post('/api/user', (req, res) => {
res.send({ msg: '新增用户成功' })
})
// PUT:更新数据(全量更新)
app.put('/api/user/:id', (req, res) => {
res.send({ msg: '更新用户成功' })
})
// DELETE:删除数据
app.delete('/api/user/:id', (req, res) => {
res.send({ msg: '删除用户成功' })
})
2. 动态路由(带参数)
// /api/user/123 → id=123
app.get('/api/user/:id', (req, res) => {
// 获取动态参数
const userId = req.params.id
res.send({ userId: userId })
})
3. 获取查询参数(? 传参)
请求示例:http://localhost:3000/api/search?keyword=express&page=1
app.get('/api/search', (req, res) => {
// 获取 ? 后的参数
const { keyword, page } = req.query
res.send({ keyword, page })
})
四、核心:请求与响应对象
1. req(请求对象)常用属性
| 属性 / 方法 | 作用 |
|---|---|
req.params |
获取动态路由参数 /user/:id |
req.query |
获取查询参数 ?name=xxx |
req.body |
获取 POST/PUT 请求体数据(需配置中间件) |
req.method |
获取请求方法(GET/POST 等) |
req.url |
获取请求路径 |
2. res(响应对象)常用方法
// 1. 发送文本/HTML
res.send('文本内容')
// 2. 发送 JSON 数据(最常用)
res.json({ code: 200, msg: '成功', data: [] })
// 3. 设置响应状态码
res.status(404).json({ msg: '资源不存在' })
// 4. 重定向
res.redirect('https://www.baidu.com')
五、核心:中间件(Middleware)
Express 最大特色:一切皆中间件,本质是处理请求的函数。
1. 中间件作用
- 解析请求体
- 处理跨域
- 日志记录
- 权限验证
- 错误捕获
2. 内置中间件(无需额外安装)
const express = require('express')
const app = express()
// 1. 解析 JSON 格式请求体(POST 提交 JSON 数据)
app.use(express.json())
// 2. 解析表单格式请求体
app.use(express.urlencoded({ extended: true }))
// 3. 托管静态资源(图片、CSS、HTML 等)
app.use(express.static('public'))
静态资源使用:创建
public文件夹,放入logo.png,访问http://localhost:3000/logo.png
3. 自定义中间件
// 全局中间件:所有请求都会经过
app.use((req, res, next) => {
console.log(`请求方法:${req.method},请求路径:${req.url}`)
next() // 必须调用 next() 放行到下一个中间件/路由
})
// 局部中间件:仅作用于指定路由
const checkToken = (req, res, next) => {
const token = req.headers.token
if (!token) return res.status(401).json({ msg: '未登录' })
next()
}
// 使用局部中间件
app.get('/api/admin', checkToken, (req, res) => {
res.json({ msg: '管理员页面' })
})
六、常用第三方中间件
1. 处理跨域(cors)
前后端分离必备,解决浏览器跨域限制:
npm install cors
const cors = require('cors')
app.use(cors()) // 允许所有跨域
2. 日志工具(morgan)
npm install morgan
const morgan = require('morgan')
app.use(morgan('dev')) // 控制台打印请求日志
3. 环境变量配置(dotenv)
管理端口、数据库地址等敏感信息:
npm install dotenv
-
创建
.env文件:PORT=4000
NODE_ENV=development -
使用:
require('dotenv').config()
const PORT = process.env.PORT || 3000
七、路由模块化(大型项目必备)
项目变大后,所有路由写在 app.js 会混乱,必须拆分路由。
1. 创建路由文件
新建 routes/user.js:
const express = require('express')
// 创建路由实例
const router = express.Router()
// 编写用户相关路由
router.get('/', (req, res) => {
res.json({ msg: '用户列表' })
})
router.post('/add', (req, res) => {
res.json({ msg: '新增用户' })
})
// 导出路由
module.exports = router
2. 主文件引入路由
app.js 中:
// 引入路由
const userRouter = require('./routes/user')
// 注册路由,添加统一前缀 /api/user
app.use('/api/user', userRouter)
最终访问路径:
http://localhost:3000/api/userhttp://localhost:3000/api/user/add
八、连接数据库(实战必备)
Express 本身无数据库,常用搭配:MySQL + Sequelize(ORM 框架)
1. 安装依赖
npm install mysql2 sequelize
2. 数据库配置
新建 config/db.js:
const { Sequelize } = require('sequelize')
// 连接数据库
const sequelize = new Sequelize('数据库名', '账号', '密码', {
host: 'localhost',
dialect: 'mysql'
})
// 测试连接
async function testConnect() {
try {
await sequelize.authenticate()
console.log('数据库连接成功')
} catch (error) {
console.log('数据库连接失败', error)
}
}
testConnect()
module.exports = sequelize
3. 定义模型(表)
新建 models/User.js:
const { DataTypes } = require('sequelize')
const sequelize = require('../config/db')
// 定义用户表模型
const User = sequelize.define('User', {
name: { type: DataTypes.STRING, allowNull: false },
age: DataTypes.INTEGER
})
// 同步表到数据库
User.sync()
module.exports = User
4. 路由中使用数据库
const User = require('../models/User')
// 查询所有用户
router.get('/', async (req, res) => {
const users = await User.findAll()
res.json({ data: users })
})
// 新增用户
router.post('/add', async (req, res) => {
const { name, age } = req.body
const user = await User.create({ name, age })
res.json({ msg: '新增成功', data: user })
})
九、错误处理中间件
统一捕获所有错误,避免服务崩溃:
// 错误处理中间件(必须放在所有路由最后)
app.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).json({
code: 500,
msg: '服务器异常',
error: err.message
})
})
十、开发效率工具:nodemon
修改代码后自动重启服务,无需手动执行 node app.js:
# 全局安装
npm install -g nodemon
# 启动服务(替代 node app.js)
nodemon app.js