I am encountering an error when trying to fetch data from my React application to an Express backend. The error message I’m receiving is: "SyntaxError: Unexpected token ‘<‘, "<!DOCTYPE "… is not valid JSON".
When I check the network tab, I see that the response is an HTML document instead of the expected JSON response. However, when I directly access the endpoint localhost:5001/test, I receive the correct JSON response.
Here’s the relevant code from my Express server:
const express = require("express");
const app = express();
app.use(express.json());
const cors = require("cors");
app.use(cors());
app.get("/test", async (req, res) => {
try {
const data = {
isActive: true,
count: 10,
message: "Hello, world!",
};
console.log(data); // Log the data being sent
res.json({ username: "Flavio", ...data });
} catch (err) {
res.send({ error: "not found" });
}
});
//React code
import React, { useState, useEffect } from "react";
export default function GetData() {
const [data, setData] = useState(null);
useEffect(() => {
fetch("/test")
.then((res) => res.json())
.then((data) => setData(data))
.catch((error) => {
console.error("Error fetching data:", error);
});
}, []);
if (data === null) {
return <Loading />;
}
return (
<div>
<h2>Data Received:</h2>
<p>isActive: {data.isActive.toString()}</p>
<p>Count: {data.count}</p>
<p>Message: {data.message}</p>
<p>Username: {data.username}</p>
</div>
);
}
Nothing is showing i dont know why
2
Answers
You have to specify the host and the port
Here is a possible explanation, (I could be wrong since I don’t have much info)
in
/test
, you maybe display info using theres.send()
function or something similar in react (I don’t do much react so I don’t know). This will generate a webpage, with all the regular HTML protocols, therefore the <!DOCUTYPE… declaring the start of the HTML document.Instead, use
res.status(200).end(yourJSONstringified)
in order to generate an status page that is not HTML, so the only content will be your JSON. I would provide a similar example in React, but I rarely do React so I am not too familiar with it.Please note, do not put a random number as the status numbers are predefined (https://en.wikipedia.org/wiki/List_of_HTTP_status_codes) in this case use like 200 or 202, not say 400, 404, or 504