I have made an API in Node and can see the data using Postman and by hiting the endpoint in the browser. But, when I try to fetch it using React, I can't see it and am getting few errors. one of them is related to the CORS, which I tried to solve by adding a proxy in the package.json of the client folder but it's still not getting solved. Here's my code:
Error:
App.js
import React, { useState, useEffect } from "react";
import "./App.css";
//Pages
//components
import Navbar from "./Components/Navbar";
function App() {
let initialData = [];
const [data, setData] = useState(initialData);
const [isFetched, setIsFetched] = useState(false);
useEffect(() => {
let headers = new Headers({
"Content-Type": "application/json",
Accept: "application/json",
});
fetch(`http://localhost:4000/`, headers)
.then((res) => res.json())
.then(
(result) => {
setData(result);
setIsFetched(true)
console.log("result"+result)
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
console.log(error);
}
);
});
return (
<div className="container">
<Navbar data={data} isFetched={isFetched} />
</div>
);
}
export default App;
NodeJs code:
const router = require('express').Router();
router.route('/').get((req, res) => {
let displayData=[{
user:'a',
id:1
},
{
user:'b',
id:2
}
]
res.status(200).json(displayData);
res.send("<h1>Home</h1>")
})
module.exports = router
server.js:
const express = require('express');
const cors = require('cors');
const { pool } = require("./db/dbConfig")
const app = express();
const port = process.env.PORT || 4000;
const homeRouter = require("./routes/home")
//middleware
app.use("/", homeRouter);
app.use(cors());
app.use(express.json());
app.listen(port, () => {
console.log(`We are live on port: ${port}`);
});