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

React前端调用Express Courses API出现404错误求助

排查React调用Express接口404错误的思路

场景说明

开发新手,当前基于本地数据开发,计划后续迁移至MongoDB。使用React前端通过axios结合useEffect调用courses接口时出现404错误,以下是具体排查步骤:


一、先验证后端接口本身是否可用

  1. 确认后端服务器已启动:查看后端终端是否输出Server listening on port 3001,若未启动,执行启动命令(如node server.js)。
  2. 直接在浏览器地址栏访问 http://localhost:3001/courses:
    • 若能返回课程JSON数据,说明后端接口正常,问题出在前端请求配置。
    • 若也返回404,说明后端路由或服务配置有问题。

二、检查前端请求地址是否正确

  1. 确认API_URL常量的取值:必须是后端服务的根地址,即http://localhost:3001(注意不要遗漏协议http://,也不要加末尾的斜杠)。
  2. 打印实际请求地址排查:在fetchCourses函数中添加日志,确认拼接后的URL是否正确:
export const fetchCourses = async () => {
  try {
    const requestUrl = `${API_URL}/courses`;
    console.log('实际请求地址:', requestUrl); // 查看控制台输出的地址
    const response = await axios.get(requestUrl);
    return response;
  } catch (error) {
    console.error('Error fetching courses:', error);
    throw error;    
  }
};

三、验证后端路由配置

  1. 检查路由文件导出与挂载:

    • 路由文件中module.exports = router导出正确,主文件中require('./routes/routes')的路径是否与实际文件位置匹配(比如路由文件是否在./routes/routes.js)。
    • 主文件中app.use('/', routes)将路由挂载在根路径,因此router.get('/courses')对应的完整接口路径就是/courses,这部分配置无明显问题,但可尝试在路由中添加根路径测试:
      // 在路由文件中添加测试接口
      router.get('/', (req, res) => {
        res.send('路由根路径正常');
      });
      
      然后访问http://localhost:3001/,看是否能返回内容,验证路由是否正常挂载。
  2. 检查中间件顺序:后端主文件中app.use('/', routes)必须放在错误处理中间件之前,当前代码顺序符合要求,无需调整。

四、通过浏览器开发者工具排查请求详情

打开浏览器F12开发者工具,切换到「Network」标签,找到courses请求:

  • 查看「Request URL」是否为http://localhost:3001/courses,若不是,说明API_URL配置错误。
  • 查看「Status Code」确认是否为404,同时查看「Response」内容,是否有后端返回的额外提示。

附用户提供的代码片段

后端路由文件(routes/routes.js)

const express = require('express');
const router = express.Router();

const courses = [
  {
    id: 1,
    title: 'Course 1',
    description: 'This is the first course',
    instructor: 'John Doe',
  },
  {
    id: 2,
    title: 'Course 2',
    description: 'This is the second course',
    instructor: 'Jane Smith',

  },
  {
    id: 3,
    title: 'Course 3',
    description: 'This is the third course test',
    instructor: 'Jane Smith',
  },
];

router.get('/courses', (req, res, next) => {
  console.log(courses)
  try {
    res.json({courses:courses});
  } catch (error) {
    next(error);
  }
});


router.get('/home', (req, res, next) => {
  try {
    res.send({ message: 'Welcome to the homepage!' });
  } catch (error) {
    next(error);
  }
});

module.exports = router;

后端主文件(server.js)

const express = require('express');
const cors = require('cors');
const routes = require('./routes/routes');

const app = express();
const port = process.env.PORT || 3001;

app.use(express.json());
app.use(cors());

app.use('/', routes);

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

前端请求函数

export const fetchCourses = async () => {
  try {
    const response = await axios.get(`${API_URL}/courses`);
    return response;
  } catch (error) {
    console.error('Error fetching courses:', error);
    throw error;    
  }
};

前端useEffect调用

useEffect(() => {
  const fetchData = async () => {
    try {
      const response = await fetchCourses();
      console.log(response.data)
      setCourses(response.data);
    } catch (error) {
      console.error('Error fetching course:', error);
    }
  };
  fetchData();
}, []);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 19:34:55