You need to enable JavaScript to run this app. NodeJS+React项目访问localhost:5000报Cannot GET / 404错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

NodeJS+React项目访问localhost:5000报Cannot GET / 404错误如何解决

问题根因

1. 中间件与路由注册顺序错误

Express的中间件、路由是按注册顺序执行的,你当前先注册了/posts路由,再注册请求解析、CORS中间件,会导致所有发往/posts的请求无法被正确预处理,部分场景下会触发404/400错误。

2. 未定义根路径路由

你当前的服务只注册了/posts前缀的路由规则,没有对根路径/做任何GET请求处理,直接访问localhost:5000必然返回404错误。你之前能看到“This works”提示是因为前期测试时写过根路由处理,后续新增post相关逻辑时删除了该段代码。

3. 控制器文件语法错误

controllers/posts.js中createPost方法的代码存在语法断裂,const关键字后直接换行、代码片段散落在标签外,会导致服务启动失败、路由无法正常响应。

修复方案

第一步:修正server/index.js的代码顺序+补全根路由

import express from 'express';
import mongoose from 'mongoose';
import cors from 'cors';

import postRoutes from './routes/posts.js';

const app = express();

// 先注册所有全局中间件
app.use(express.json({ limit: "30mb", extended: true }));
app.use(express.urlencoded({ limit: "30mb", extended: true }));
app.use(cors());

// 再注册业务路由
app.use('/posts', postRoutes);

// 补全根路由处理,适配你之前的测试逻辑
app.get('/', (req, res) => {
  res.send('This works');
})

const CONNECTION_URL = 'mongodb+srv://*****:******@cluster0.kwo9h.mongodb.net/myFirstDatabase?retryWrites=true&w=majority'
const PORT = process.env.PORT || 5000;

mongoose.connect(CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => app.listen(PORT, () => console.log(`Server running on port: ${PORT}`)))
    .catch((error) => console.log(error.message));

mongoose.set('useFindAndModify', false);

第二步:修正controllers/posts.js的语法错误

import PostMessage from '../models/postMessage.js';

export const getPosts = async (req, res) => {
    try {
        const postMessages = await PostMessage.find();
        res.status(200).json(postMessages);
    } catch (error) {
        res.status(404).json({ message: error.message });
    }
}

export const createPost = async (req, res) => {
    // 把散落的post变量声明挪回函数内部,修正断裂的语法
    const post = req.body;
    const newPost = new PostMessage(post);
    try {
        await newPost.save();
        res.status(201).json(newPost);
    } catch (error) {
        res.status(409).json({ message: error.message });
    }
}

第三步:验证

重启Node服务后:

  • 访问localhost:5000可正常返回“This works”
  • 访问localhost:5000/posts可正常返回存储的帖子数组数据
  • 前端JSX请求接口时请确认请求地址为/posts而非根路径,即可正常拉取数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 09:06:05