我已经使用expressjs在nodejs中编写了后端代码,并且我在mongodb数据库中存储了一个医生列表,并且我正在使用mongoose。我已经在邮递员中测试了 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;
你可以在react中使用fetch方法来获取所有数据
const [data, setData] = useState([])
await fetch('url')
.then((res) => res.json())
.then((result) => useData(result))
使用相对路径,如
/api/doctors
如果您的服务器运行在与 React 应用程序不同的端口上,请尝试设置代理 - https://create-react-app.dev/docs/proxying-api-requests-in-development/
我建议阅读整个页面,但重要的部分是将其放入管理你的 React 应用程序的 package.json 中。
来自文档:
“要告诉开发服务器将任何未知请求代理到开发中的 API 服务器,请在 package.json 中添加代理字段,例如:
"proxy": "http://localhost:4000",
”
console.log(“你好”)