Node.js 后端开发之 Express 处理 API 请求
Hello World
npm init -y # 新建项目
npm install express # 安装 Express
app.js:
import express from 'express';
const app = express();
const port = 3000;
// 定义一个 GET 路由
app.get('/', (req, res) => {
res.send('Hello, Express!');
});
// 监听端口
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
启动服务:
$ node app.js
$ curl http://localhost:3000
Hello, Express!
路由
// GET 路由
app.get('/about', (req, res) => {
res.send('About Page');
});
// POST 路由
app.post('/contact', (req, res) => {
res.send('Contact Page');
});
// 链式挂载,同时配置多个路由
app.route(path).get(handler).post(handler);
获取参数
-
路由参数:
// :word 是参数 app.get("/:word/echo", (req, res) => { const { word } = req.params; // 获取参数值 res.json({echo: word}); });访问 http://localhost:3000/anything/echo 会得到
{echo: anything} -
查询字符串:
app.get("/name", (req, res) => { const { first, last } = req.query; // 从查询字符串中提取参数 res.json({name: `${first} ${last}`}); });访问 http://localhost:3000/?first=John&last=Connor 会得到
{name: John Connor} -
从 POST 请求中获取 body 数据:
app.use(express.json()); // 处理 POST 请求体的 JSON 数据。 app.use(express.urlencoded({extended: false})); // 处理 POST 请求体的 URL 编码数据 app.get("/name", (req, res) => { const { first, last } = req.body; res.json({name : `${first} ${last}`}); });使用 Axios 发送测试数据:
import axios from 'axios'; const data = { first: "John", last: "Connor" }; axios.post('http://localhost:3000/name', data) .then(response => { // 正常响应 console.log('Response:', response.data); }) .catch(error => { // 错误处理 console.error('Error:', error.response.data); });
中间件
// 使用中间件来记录每个请求的时间
app.use((req, res, next) => {
console.log('Time:', Date.now());
next();
});
处理静态文件
app.use(express.static('public'));
参见:

浙公网安备 33010602011771号