I have an API endpoint located on my localhost:8000/
port; this endpoint simply returns the following object {"message": "hello"}
.
I would like to grab this object using my React JS script. My script is added below.
import React, {useEffect, useState} from "react";
const App = () => {
const [message, setMessage] = useState("");
const getHomePageData = async () => {
const requestOptions = {
method: "GET",
headers: {
"Content-Type": "application/json",
},
};
const response = await fetch("/", requestOptions)
if (!response.ok) {
console.log("Error in fetching the data!");
} else {
console.log("Data fetched correctly!");
}
return await response.json();
};
const data = getHomePageData();
console.log(data);
return(
<center><h1>Hello, world!</h1></center>
);
}
export default App;
Fetching the data seems to be working, because I'm getting the following log inside the console: Data fetched correctly!
thus I think everything is working alright with my backend. However on the next line I get the following error message: Unhandled Promise Rejection: SyntaxError: The string did not match the expected pattern.
How can I fix my code to be able to get the .json()
data?