
本文详解 express 服务端路由定义、mongoose 连接配置及前端 fetch 调用实践,涵盖 post/get/put 接口实现、错误处理、id 校验与 dom 动态渲染,助你快速解决 url 不可达、404 或 cors 等常见联调问题。
本文详解 express 服务端路由定义、mongoose 连接配置及前端 fetch 调用实践,涵盖 post/get/put 接口实现、错误处理、id 校验与 dom 动态渲染,助你快速解决 url 不可达、404 或 cors 等常见联调问题。
在构建基于 Express 和 Mongoose 的 RESTful API 时,URL 无法访问(如 404 Not Found、500 Internal Server Error)通常并非单一原因所致,而是涉及服务启动、路由注册、中间件顺序、数据库连接状态及前后端请求路径一致性等多个环节。以下为系统性排查与优化方案:
✅ 1. 确保服务已正确启动并监听端口
你的代码中缺少 app.listen() —— 这是导致“URL 不工作”的最常见疏漏。请在文件末尾添加:
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Servidor corriendo en http://localhost:${PORT}`);
});
⚠️ 注意:若未调用
listen(),Express 应用仅初始化而不会接收任何 HTTP 请求,所有前端fetch('/tasasDeCambio')均会超时或返回ERR_CONNECTION_REFUSED。
✅ 2. 检查路由注册顺序与中间件位置
你已正确使用 bodyParser,但需确保其位于所有路由定义之前(当前代码符合)。此外,建议统一启用 express.json() 和 express.urlencoded()(body-parser 已内置):
当代理已经知道网站路由或内容URL,并且在启动前需要有效的sitemap XML、sitemap索引或robots.txt引用时,请使用sitemap。这是一个发布构件技能,而不是爬虫或SEO平台。
app.use(express.json()); // 替代 bodyParser.json()
app.use(express.urlencoded({ extended: true })); // 替代 bodyParser.urlencoded()
app.use(express.static(path.join(__dirname, 'public')));
✅ 3. 验证 Mongoose 连接与模型定义
- 确保 MongoDB 服务正在运行(
mongod进程活跃); - 检查
TasasDeCambio模型是否正确定义 Schema 并导出(示例):
// ./server/models/TasasDeCambio.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const TasasDeCambioSchema = new Schema({
moneda: { type: String, required: true },
tasa: { type: Number, required: true }
}, { timestamps: true });
module.exports = mongoose.model('TasasDeCambio', TasasDeCambioSchema);
? 提示:Mongoose
connect()的.then()仅表示连接建立成功,不保证后续路由立即可用;务必确认app.listen()在连接成功回调内或之后执行(推荐用async/await封装)。
✅ 4. 前端调用必须匹配后端路由规则
你提供的前端 JS 使用了标准 Fetch,但存在两个关键细节需修正:
-
ID 字段名不一致:后端
findByIdAndUpdate使用req.params.tasaId,但前端actualizarTasaDeCambio(tasa.id)中tasa.id应为tasa._id(MongoDB 默认主键字段为_id,非id); -
缺失 PUT 请求体序列化:
fetch()发送 PUT 时需显式设置method、headers和body:
function actualizarTasaDeCambio(id) {
const tasaInput = document.getElementById(`tasa-${id}`);
const nuevaTasa = parseFloat(tasaInput.value);
fetch(`/tasasDeCambio/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
moneda: 'USD', // 实际应从数据源读取,此处仅为示意
tasa: nuevaTasa
})
})
.then(res => res.json())
.then(data => {
alert('Actualizado correctamente');
location.reload(); // 或重新调用 obtenerTasasDeCambio()
})
.catch(err => console.error('Error al actualizar:', err));
}
✅ 5. 补充健壮性措施(生产就绪建议)
- 添加全局 404 处理器(放在所有路由之后):
app.use('*', (req, res) => { res.status(404).json({ message: 'Ruta no encontrada' }); }); - 启用 CORS(若前端不在同域):
npm install cors
const cors = require('cors'); app.use(cors()); // 开发阶段可接受;生产环境应配置 origin 白名单
✅ 总结检查清单
| 项目 | 是否完成 |
|---|---|
✅ app.listen() 已调用且端口未被占用 |
☐ |
| ✅ MongoDB 正在运行,连接字符串正确 | ☐ |
✅ 所有路由路径(如 /tasasDeCambio)与前端 fetch() 完全一致(含大小写、斜杠) |
☐ |
✅ 前端使用 tasa._id 而非 tasa.id 传递 ID |
☐ |
✅ PUT/POST 请求设置了 Content-Type: application/json 并 JSON.stringify() body |
☐ |
✅ 浏览器控制台与终端日志无 ERR_CONNECTION_REFUSED 或 MongooseServerSelectionError
|
☐ |
遵循以上步骤,你的 Express + Mongoose 应用 URL 将稳定响应,前后端协同工作流畅。对于哈佛课程项目,建议进一步补充单元测试(如 Jest + Supertest)和环境变量管理(.env),以提升工程规范性。










