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

ReactJS使用Axios获取数据渲染表格报Cannot GET错误排查

问题排查与修复方案

Cannot GET /api/get/week1 是标准的后端接口404响应,代表请求已经成功送达后端,但后端没有匹配到该路径的GET处理逻辑,不是Axios本身的调用错误。

验证猜想的方法

不用先改前端代码,两步就能定位问题归属:

  • 直接在浏览器地址栏输入 http://localhost:3001/api/get/week1 回车访问,如果页面同样显示「Cannot GET /api/get/week1」,可以100%确定问题出在后端路由配置,和前端Axios无关
  • 打开浏览器F12开发者工具,切换到Network面板,刷新页面找到该请求,查看响应状态码为404、响应内容为上述报错文本,也能佐证请求发送环节正常,是后端未提供对应接口
  • 后端侧需要排查:是否注册了路径为/api/get/week1的GET路由、是否存在全局路由前缀重复拼接(比如全局挂载了/api前缀,路由定义里又写了/api/get/week1导致实际路径变成/api/api/get/week1)、服务是否真的监听在3001端口。

现有前端代码的Bug修复

你写的BookingTable组件本身有3个会导致渲染异常的问题,和接口报错无关,但必须修正:

  1. React Hook声明顺序错误:useState 必须写在useEffect前面,Hook在组件顶层要按固定顺序声明,否则会触发React的Hook规则报错
  2. 表格渲染函数未执行:<tbody>里写的{renderTableData}只是传入了函数引用,没有执行函数拿返回的JSX,要改成{renderTableData()}
  3. 无效DOM属性:<tr class>是无效写法,没有给class传值,直接删掉多余的class属性即可
  4. 列表渲染缺少key属性:循环生成tr标签时需要加唯一key值,避免React渲染警告

接口返回数组有效性校验方法

在Axios请求回调里加格式校验和错误捕获,避免异常格式数据导致页面崩溃:

useEffect(() => {
  Axios.get('http://localhost:3001/api/get/week1')
    .then((response) => {
      // 校验返回值是否为预期的数组格式
      if (Array.isArray(response.data)) {
        setIsBooked(response.data)
        console.log('获取到的有效预约数据:', response.data)
      } else {
        console.error('接口返回格式异常,预期为数组,实际返回:', response.data)
        setIsBooked([])
      }
    })
    .catch((err) => {
      // 捕获网络错误、404/500等HTTP错误
      console.error('预约数据请求失败,状态码:', err.response?.status, '错误信息:', err.message)
      setIsBooked([])
    })
}, [])

渲染时也可以加空状态兜底,数据为空时显示提示:

const renderTableData = () => {
  if (isBooked.length === 0) {
    return <tr><td colSpan={1}>暂无已预约时段</td></tr>
  }
  return isBooked.map((val, index) => (
    <tr key={index}>
      <td>{val.booked}</td>
    </tr>
  ))
}

修复后的完整组件代码

import { useEffect, useState } from 'react'
import Axios from 'axios'

function BookingTable() {
  // useState必须放在useEffect之前声明
  const [isBooked, setIsBooked] = useState([])

  useEffect(() => {
    Axios.get('http://localhost:3001/api/get/week1')
      .then((response) => {
        if (Array.isArray(response.data)) {
          setIsBooked(response.data)
        } else {
          setIsBooked([])
        }
      })
      .catch(() => {
        setIsBooked([])
      })
  }, [])

  const renderTableData = () => {
    if (isBooked.length === 0) {
      return <tr><td>暂无已预约时段</td></tr>
    }
    return isBooked.map((val, index) => (
      <tr key={index}>
        <td>{val.booked}</td>
      </tr>
    ))
  }

  return (
    <table id="table">
      <thead>
        <tr>
          <th>已预约时段</th>
        </tr>
      </thead>
      <tbody>
        {/* 注意要加()执行渲染函数 */}
        {renderTableData()}
      </tbody>
    </table>
  )
}

export default BookingTable

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 01:27:28