skip to Main Content

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


  1. The error you are receiving is:

    Error fetching data

    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:

    new ApiResponse(200, data, "Data Sent Successfully!!")

    Then, the error falls into your route’s catch and is returned to the front-end.

    Login or Signup to reply.
  2. 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:

    1. The backend might not be sending the response with the correct content type header or might not be formatting the response as JSON.
    2. There could be an error on the server side that is causing it to return an HTML error page instead of the expected JSON response.
    3. If there’s a middleware or proxy between the frontend and backend, it might be modifying the response or not forwarding the correct headers.

    To troubleshoot this issue:

    1. Ensure that the backend code is correctly setting the Content-Type header to application/json before sending the response.
    2. Use browser developer tools to inspect the network request and response. Check the response headers and body to see if they match what you expect.
    3. Add logging on the backend side to log the response headers and body before sending them. This can help identify any discrepancies.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search