
本文介绍如何使用 express 构建 restful 路由,通过 url 参数(如 `/user/5`)接收用户 id,并返回对应用户数据;同时支持直接在浏览器中访问调试,适用于 mongodb 等常见数据库场景。
要实现类似 http://localhost:3000/user/5 这样的浏览器可访问接口,并返回结构化用户信息(如 User id: 5 Name: Ann),你需要在后端定义一条动态路由,提取 URL 中的用户 ID,查询数据库,并以清晰格式响应。
首先,确保你已安装并配置好 Express 和对应数据库驱动(如 Mongoose)。以下是一个完整、可运行的示例:
// app.js(或你的主路由文件) const express = require('express'); const mongoose = require('mongoose'); const app = express(); // 示例 User 模型(假设使用 MongoDB + Mongoose) const userSchema = new mongoose.Schema({ name: String, email: String, }); const User = mongoose.model('User', userSchema); // 解析 JSON 请求体(即使 GET 不需要,也建议保留) app.use(express.json()); app.use(express.urlencoded({ extended: true })); // ✅ 核心路由:匹配 /user/:id(支持 /user/5、/user/123 等) app.get('/user/:id', async (req, res) => { try { const { id } = req.params; // 验证 ID 格式(防止无效 ObjectId 或非数字 ID) if (!id || !/^d+$/.test(id)) { return res.status(400).send('Invalid user ID: must be a positive number'); } const user = await User.findById(id).select('name email _id'); // 仅返回必要字段 if (!user) { return res.status(404).send('User not found'); } // 返回简洁、易读的 html 片段(适配浏览器直访) res.send(` User details
User id: ${user._id}
Name: ${user.name || 'N/A'}
Email: ${user.email || 'N/A'}
`); } catch (err) { console.error(err); res.status(500).send('Internal server error'); } }); // 启动服务 const PORT = 3000; app.listen(PORT, () => { console.log(`Server running at http://localhost:${PORT}`); });
? 关键说明与注意事项:
- :id 是 Express 的路径参数语法,req.params.id 可安全提取 URL 中的值;
- 实际生产环境建议使用 ObjectId(mongodb 原生 _id)而非纯数字 ID,此时应改用 mongoose.Types.ObjectId.isValid(id) 校验;
- 浏览器直接访问时,返回 HTML 字符串比 jsON 更友好(如需 API 兼容,可添加 Accept: application/json 判定响应格式);
- 务必添加错误处理(404、500、参数校验),避免敏感错误堆栈暴露给前端;
- 若使用其他数据库(如 postgresql、mysql),只需将 User.findById(id) 替换为对应 ORM 查询方法(如 User.findByPk(id) 或 SELECT * FROM users WHERE id = ?)。
完成上述配置后,启动服务,在浏览器中访问 http://localhost:3000/user/5,即可看到格式化的用户详情页——简洁、可靠、开箱即用。