Express 是一个轻量级 Node.js Web 框架,构建在 http 模块之上,封装路由、中间件等逻辑,不内置模板引擎或数据库支持;需通过 require('express') 实例化 app 后定义路由并调用 app.listen() 启动服务。
Express 不是独立运行的服务器,而是构建在 http 模块之上的框架,用来简化路由、中间件、请求处理等常见任务。它本身不包含模板引擎、数据库连接或身份验证——这些都靠第三方包或你自己实现。
你写 app.get('/') 时,Express 在底层调用的是 http.createServer(),但帮你把 URL 解析、方法匹配、参数提取这些重复逻辑封装好了。
确保已安装 Node.js(v18+ 推荐),然后执行:
npm init -y npm install express
新建 server.js:
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send('Hello from Express!');
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
运行:node server.js。访问 http://localhost:3000 就能看到响应。
require('express') 和 express() 实例化,否则 app.get 会报 TypeError: Cannot read property 'get' of undefined
app.listen() 必须在所有路由定义之后调用,否则路由不会生效nodemon 自动重启:npm install -D nodemo
n,然后用 npx nodemon server.js
三个高频问题对应三种不同原因:
EADDRINUSE :::3000:端口被占用。改端口(如 3001)或杀掉进程:lsof -i :3000(macOS/Linux)或 netstat -ano | findstr :3000(Windows)res.send()、res.json() 或 res.end() —— Express 不会自动结束响应,挂起连接会导致超时/api/users 返回 404:确认路由路径和 HTTP 方法完全匹配,app.post('/api/users') 不会响应 GET 请求中间件函数必须调用 next(),否则请求会卡住。比如日志中间件:
app.use((req, res, next) => {
console.log(`${new Date().toISOString()} ${req.method} ${req.url}`);
next(); // ⚠️ 这行不能少
});
静态文件服务也依赖中间件:
app.use(express.static('public')); // 会自动 serve public/index.html
express.json() 和 express.urlencoded({ extended: true }) 必须在使用 req.body 前注册,否则 req.body 是 undefined
next(new Error('xxx')))会被 Express 默认错误处理器捕获,但生产环境应替换为自定义错误处理中间件app.get('/user', authMiddleware, handler) 中的 authMiddleware 只跑在该路由server.js —— 等到加个登录、连个 MongoDB、再套层 JWT,结构就失控了。拆分路由、抽离配置、提前规划错误流,比选什么 ORM 更早该考虑。