mongodb 无法在react js前端呈现来自mongo db的数据

mzsu5hc0  于 2023-03-17  发布在  Go
关注(0)|答案(2)|浏览(97)

我用expressjs在nodejs写了一个后端代码,我有一个医生列表存储在mongodb数据库中,我用的是mongoose。我在postman测试了API端点,我得到了正确的输出,但是当我试图在reactjs应用程序中呈现相同的数据时,我得到了空表。有人能帮我吗?
下面是我的代码。
以下是后端代码

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"));

这是react前端代码

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;
w7t8yxp5

w7t8yxp51#

可以在react中使用fetch方法获取所有数据

const [data, setData] = useState([])
await fetch('url')
  .then((res) => res.json())
  .then((result) => useData(result))
flvlnr44

flvlnr442#

使用相对路径,如/api/doctors
如果服务器运行的端口与react应用程序不同,请尝试设置代理-https://create-react-app.dev/docs/proxying-api-requests-in-development/
我建议阅读整个页面,但重要的是将其放在管理react应用程序的package.json中。
来自文档:
“要告诉开发服务器将任何未知请求代理到正在开发的API服务器,请在package.json中添加一个proxy字段,例如:
"proxy": "http://localhost:4000",英寸

相关问题