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

React前端无法渲染MongoDB数据求助:后端API正常但前端表格为空

问题排查:React调用Express接口后页面显示空表格

我使用Node.js结合Express与Mongoose搭建后端,MongoDB数据库中存储了医生列表数据。通过Postman测试/api/doctors接口时能正常获取正确数据,但在React应用中调用该接口后,页面始终显示空表格,请求帮忙排查问题。

后端代码

const mongoose = require("mongoose");
const express = require("express");
const app = express();

mongoose
  .connect("mongodb://localhost/mongo-exercises")
  .then(() => console.log("Connected to Mongo DB"))
  .catch((err) => console.error("Could not connect to mongo db", err));

const doctorSchema = new mongoose.Schema({
  serialNumber: Number,
  yearOfRegistration: Number,
  registrationNumber: String,
  medicalCouncil: String,
  name: String,
  fathersName: String,
});

const Doctor = mongoose.model("Doctor", doctorSchema);

app.get("/api/doctors", async (req, res) => {
  const doctors = await Doctor.find();
  res.send(doctors);
});

app.listen(6000, () => console.log("listening on port 6000"));

前端代码

import axios from "axios";
import React, { Component } from "react";

class Doctors extends Component {
  state = {
    posts: [],
  };
  
  async componentDidMount() {
    const { data: posts } = await axios.get(
      "http://localhost:6000/api/doctors"
    );
    this.setState({ posts });
  }

  render() {
    return (
      <div className="m-2">
        <table className="table">
          <thead>
            <tr>
              <th>Serial Number</th>
              <th>Year of Registration</th>
              <th>Registration Number</th>
              <th>Name</th>
              <th>Medical Council</th>
              <th>Father's Name</th>
            </tr>
          </thead>
          <tbody>
            {this.state.posts.map((post) => (
              <tr key={post._id}>
                <td>{post.serialNumber}</td>
                <td>{post.yearOfRegistration}</td>
                <td>{post.registrationNumber}</td>
                <td>{post.medicalCouncil}</td>
                <td>{post.name}</td>
                <td>{post.fathersName}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );
  }
}

export default Doctors;

可能的原因及解决办法

1. 跨域请求被拦截(最常见)

Postman不受浏览器同源策略限制,但React前端在浏览器环境下会触发跨域校验,后端未配置CORS的话,浏览器会直接拦截请求,导致数据无法获取。

  • 解决:安装并启用cors中间件
    1. 安装依赖:
      npm install cors
      
    2. 后端代码中添加配置:
      const cors = require("cors");
      app.use(cors()); // 必须放在路由定义之前
      

2. 请求失败未捕获

当前前端代码没有错误处理逻辑,请求可能已经失败但未被察觉,导致状态未更新。

  • 解决:添加错误捕获并打印日志,方便排查
    async componentDidMount() {
      try {
        const { data: posts } = await axios.get("http://localhost:6000/api/doctors");
        console.log("接口返回数据:", posts); // 确认是否拿到数据
        this.setState({ posts });
      } catch (error) {
        console.error("请求接口失败:", error.message);
      }
    }
    

3. 字段名不匹配

检查后端返回的字段与前端渲染时使用的字段是否完全一致(注意大小写、拼写、下划线等细节),比如后端返回的serialNumber是否确实存在,有没有写成serial_number。

  • 解决:在浏览器开发者工具的「Network」面板查看接口返回的Response数据,对比前端代码中的字段名。

4. 状态更新或组件渲染问题

确认setState是否正确更新了组件状态,或者组件是否因某种原因未重新渲染。

  • 解决:在render方法中打印状态数据,确认是否已更新:
    render() {
      console.log("当前状态数据:", this.state.posts);
      // ... 原有渲染代码
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 09:45:00