Express.js Cheatsheet - Express Middleware & API Reference
All essential Express.js commands organized by use case, with 45+ entries you can copy and run directly. Find the right command fast when you need it.
Back to LanguagesApp Creation 5
const app = express()Create应用实例
app.use(express.json())挂载全局middleware(解析 JSON request体)
app.listen(3000, () => {})监听PortStartService
const router = express.Router()Create可挂载route器
app.set("port", process.env.PORT || 3000)Set应用Configure
Routes 7
app.get("/users", handler)GET route
app.post("/users", handler)POST route
app.put("/users/:id", handler)PUT route,:id 是Options
app.delete("/users/:id", handler)DELETE route
app.all("/api/*", handler)Match所有method的通配route
app.use("/api", router)挂载子routemodule
router.route("/users").get(list).post(create)链式route定义
Request 6
req.params.idURL routeOptions
req.query.page查询stringOptions
req.body.namerequest体(需 express.json())
req.headers["content-type"]request头
req.cookies.tokenCookie(需 cookie-parser)
req.get("User-Agent")Get指定request头
Response 6
res.send("hello")发送文本response
res.json({ data })返回 JSON
res.status(201).json({ ok: true })Setstate码并返回 JSON
res.redirect("/login")redirect
res.sendFile(path.join(__dirname, "index.html"))发送File
res.set("X-Custom", "value")Setresponse头
Middleware 8
app.use((req, res, next) => { next() })自定义middleware
express.urlencoded({ extended: true })解析 URL 编码表单
app.use("/static", express.static("public"))静态FileService
cors()跨域supportsmiddleware
helmet()安全 HTTP 头middleware
morgan("dev")request日志middleware
cookie-parser()解析 Cookie
compression()responseCompressmiddleware
JWT 6
app.set("view engine", "ejs")Settemplate引擎
app.set("views", path.join(__dirname, "views"))SettemplateDirectory
res.render("index", { title: "Home" })rendertemplate并response
jwt.sign(payload, secret, { expiresIn: "1h" })签发 JWT token
jwt.verify(token, secret)验证 JWT token
req.headers.authorization从request头Get Bearer token
Errors & Patterns 7
const wrap = (fn) => (req, res, next) => fn(req, res, next).catch(next)async错误package装器,自动catch async 错误
app.use((req, res) => res.status(404).send("Not Found"))404 fallback处理
app.use((err, req, res, next) => res.status(500).json({ error: err.message }))全局错误处理middleware(必须 4 个Options)
next(err)传递错误到错误处理middleware
process.on("uncaughtException", handler)catch未处理exception
process.on("unhandledRejection", handler)catch未处理 Promise 拒绝
module.exports = routerExportroutemodule供 app.use 挂载
💡 Tips
- middlewareorder很重要,body-parser 必须在route之前,错误处理middleware必须放最后。
- 错误处理middleware必须 4 个Options (err, req, res, next),否则 Express 不识别。
- 生产环境用 helmet() 加安全头,cors() 按需Configure白名单。
- express.static 可Set多个Directory,按orderFindFile。
- Router 可module化route,app.use("/api", router) 挂载子route。
Official References
Commands are compiled from the official docs below. Click to verify the latest usage.
Maintained by LaoHand
Publicly updated on Jul 21, 2026, continuously proofread against official docs.
Found an error? Report it
Wrong command or description? Open an issue to help us fix it.
Found an error? Report it