I’m a beginner in the MERN stack. Just started a project and I’m trying to fetch data from my express server to my react server. I used vite to start up the react local server.
However, this is the error message I keep getting in the console, and I’m unable to fetch the data from the backend server
–Backend (index.js)–
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const app = express();
app.use(express.json());
const PORT = process.env.PORT || 4000;
app.get("/", (req, res) => {
res.json("Running on MERN Deploy Practice");
console.log("Active now????");
});
app.get("/message", (req, res) => {
res.json({
"items": ["user1", "user2", "user3"]
});
});
app.listen(PORT, () => {
console.log(`Server is Running at ${PORT}`);
});
–Frontend (App.jsx)–
import { useState, useEffect } from "react";
import "./App.css";
function App() {
const [message, setMessage] = useState([ ]);
useEffect(() => {
fetch("/message")
.then((res) => res.json())
.then((data) => setMessage(data));
}, []);
;
return (
<div>
<h1>Hello User</h1>
{(typeof message.items === 'undefined') ? (
<p>Loading...</p>
) : (
message.items.map((item, i) => (
<p key={i}>{item}</p>
))
)}
<h1>{message}</h1>
</div>
);
}
export default App
Here’s the file paths
I’ve tried using the JSON.parse() and JSON.stringify() for the data but still not working.