You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

搭建MERN栈网站遇404错误,请求排查路由配置问题

排查与修复方案

1. 修复服务器路由挂载路径

你的服务器文件中挂载路由时缺少前缀斜杠,导致路由无法正确匹配:

// 错误写法
app.use('events', eventsRouter);

// 正确写法
app.use('/events', eventsRouter);

Express的app.use()路径参数需要以/开头,否则会被当作相对路径处理,无法匹配/events请求。

2. 重构路由文件(routes/events.js)

你当前的路由文件完全复制了服务器代码,这是严重错误。路由文件应仅负责定义特定路径的API接口,而非重复创建Express实例、连接数据库或启动服务器。正确示例:

const express = require('express');
const router = express.Router();
// 引入事件模型(需自行创建models/Event.js)
const Event = require('../models/Event');

// 获取所有事件的GET接口
router.get('/', async (req, res) => {
  try {
    const events = await Event.find();
    res.json(events);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

// 创建事件的POST接口
router.post('/', async (req, res) => {
  const event = new Event({
    title: req.body.title,
    date: req.body.date
    // 其他字段根据你的模型定义添加
  });

  try {
    const newEvent = await event.save();
    res.status(201).json(newEvent);
  } catch (err) {
    res.status(400).json({ message: err.message });
  }
});

module.exports = router;

同时需在models目录下创建Event.js模型文件:

const mongoose = require('mongoose');

const eventSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true
  },
  date: {
    type: Date,
    required: true
  }
  // 其他字段按需添加
});

module.exports = mongoose.model('Event', eventSchema);

3. 解决前端路由404问题

启动服务器后访问/出现Cannot GET /,是因为Express未处理前端路由请求。开发环境可在前端package.json中添加代理配置:

// 前端package.json中新增
"proxy": "http://localhost:3000"

生产环境则需在服务器中托管前端静态文件并添加fallback路由:

// 服务器文件中,路由挂载后添加
const path = require('path');
// 托管前端构建产物(假设构建文件在client/build目录)
app.use(express.static(path.join(__dirname, 'client/build')));

// 所有非API请求返回前端index.html,支持React路由
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});

4. 统一请求路径大小写

你提到发送GET请求时出现Cannot GET /Events错误,Express路由大小写敏感,确保请求路径为小写的/events,与服务器配置一致。

验证步骤

  1. 重启服务器,确认MongoDB连接正常
  2. 用Insomnia测试GET http://localhost:3000/events,应返回MongoDB中的事件数据
  3. 测试POST http://localhost:3000/events,发送符合模型结构的JSON数据,应能创建新事件并返回结果

内容的提问来源于stack exchange,提问作者Gua

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 09:53:10