I have developed Backend in NodeJS and Frontend in ReactJS. I have hosted the backend on my own pc. When I am accessing the Data from postman It is giving me JSON Data but when I am fetching the data on frontend, Api is giving html/text Data.
Frontend Code
class Auth {
async fetchData() {
try {
const response = await fetch('/data/get-data', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
});
console.log("DEBUG : response", response); // Log the entire response object
if (!response.ok) {
throw new Error(`Failed to fetch data: Status code ${response.status}`);
}
const contentType = response.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) {
throw new Error('Unexpected content type: ' + contentType);
}
const jsonData = await response.json();
console.log("DEBUG : jsonData", jsonData);
return jsonData;
} catch (error) {
console.error('Error fetching data:', error);
// Optionally handle errors gracefully on the frontend (e.g., display an error message)
}
}
}
const authService = new Auth();
export default authService
Backend Code
import { asyncHandler } from '../utils/asyncHandler.js';
import { ApiResponse } from '../utils/apiResponse.js';
import { Data } from '../models/data.model.js';
import { ApiErrors } from '../utils/ApiErrors.js';
const getData = asyncHandler(
async (req, res) => {
try {
const data = await Data.find();
console.log("nSuccessfully retrieved data...");
res.setHeader('Content-Type', 'application/json');
return res
.status(200)
.json(new ApiResponse(200, data, "Data Sent Successfully!!"));
} catch (error) {
console.error('Error while fetching data:', error);
const apiError = new ApiErrors(500, 'Internal Server Error');
return res.status(apiError.statusCode).json(apiError);
}
}
);
export { getData };
Error
auth.js:25 Error fetching data: Error: Unexpected content type: text/html
I am new to MERN. Please help
2
Answers
The error you are receiving is:
That is, it is an error on the back-end side that is being sent to the front-end. There is probably an error elsewhere in your backend code, such as:
Then, the error falls into your route’s catch and is returned to the front-end.
The error "Unexpected content type: text/html" suggests that the response from the server is not returning JSON as expected by the frontend code. This could happen due to several reasons:
To troubleshoot this issue: