I have written a backend code in nodejs using expressjs and I have a list of doctors stored in mongodb database and I am using mongoose. I have tested the api end point in postman and I am getting correct output there but when I try to render the same data in my reactjs app then I get empty table.
Can anyone help me with this?
Following is my code.
Following is the backend code
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"));
and this is the react front end code
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;
2
Answers
you can use fetch method in react to get all data
Use relative paths like
/api/doctors
If your server is running on a different port than your react app, try setting up a proxy – https://create-react-app.dev/docs/proxying-api-requests-in-development/
I would recommend reading the whole page, but the important part is to put this in the package.json that is managing your react app.
From the docs:
"To tell the development server to proxy any unknown requests to your API server in development, add a proxy field to your package.json, for example:
"proxy": "http://localhost:4000",
"