Express.js 常用命令速查表

把 Express 日常开发最常用的路由和中间件整理成速查,写 API 时对照查。

编程语言·共 31 条命令·最后更新 2026-07-19
返回 编程语言

基础路由 6

app.get("/", (req, res) => {})
GET 路由
app.post("/api/users", (req, res) => {})
POST 路由
app.put("/api/users/:id", (req, res) => {})
PUT 路由
app.delete("/api/users/:id", (req, res) => {})
DELETE 路由
app.all("/api/*", (req, res) => {})
匹配所有方法
app.use("/api", router)
挂载子路由

请求与响应 8

req.body
请求体(需 body-parser)
req.params.id
URL 参数
req.query.page
查询字符串参数
req.headers["content-type"]
请求头
res.json({ data })
返回 JSON
res.status(404).send("Not Found")
返回状态码+文本
res.redirect("/login")
重定向
res.sendFile(path)
发送文件

常用中间件 8

express.json()
解析 JSON 请求体
express.urlencoded({ extended: true })
解析 URL 编码
express.static("public")
静态文件服务
cors()
跨域支持
helmet()
安全头
morgan("dev")
请求日志
cookie-parser()
解析 cookie
compression()
响应压缩

错误处理 5

app.use((err, req, res, next) => {})
全局错误处理中间件
next(err)
传递错误到错误处理
app.use((req, res) => res.status(404).send("Not Found"))
404 处理
process.on("uncaughtException", handler)
捕获未处理异常
process.on("unhandledRejection", handler)
捕获未处理 Promise 拒绝

JWT 鉴权 4

jwt.sign(payload, secret, { expiresIn: "1h" })
签发 token
jwt.verify(token, secret)
验证 token
app.use((req, res, next) => { /* 检查 token */ })
鉴权中间件
req.headers.authorization
从请求头获取 token

💡 提示

  • Express 4.x 开始 body-parser 已内置,用 express.json() 即可。
  • 错误处理中间件必须有 4 个参数 (err, req, res, next),否则 Express 不识别。
  • 生产环境用 helmet() 加安全头,cors() 按需配置白名单。