Fetch -API returning HTML instead of JSON

41,527

Solution 1

Header is not correct. Valid header for JSON response:

headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  }

Solution 2

Sometimes Apis return html instead of json if you are not logged in, confirm that as well

Share:
41,527
Afsar
Author by

Afsar

A full-stack developer.

Updated on July 11, 2022

Comments

  • Afsar
    Afsar almost 2 years

    I have a Spring REST API which I've tested on Postman and it returns perfectly valid JSON. However when I call the same API on my front-end React Code it returns HTML. This is the function, I'm using to call the API,

    export function run(engine, mediaId, owner, target, access){
      let url = engine + "/" + mediaId + "?id=" + owner + "&targetId=" + target + "&access=" + access;
    
      return fetch(full_url, { credentials: "include",
                               headers: {
                                 "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
                              }})
        .then((response) => {
    
          return response.json();})
        .then((data) => {
            console.log(data);
    
        })
        .catch((error) => {
            console.log(error);
        });
    }
    

    I get a syntax error on this call Unexpected token < Thus when I check using response.text() I can see that the data returned is HTML and not JSON. What do I need to change in my front-end code for the API to return JSON.

    • Janaka Dissanayake
      Janaka Dissanayake over 7 years
      please try "Content-Type" : "text/plain"
    • G H Prakash
      G H Prakash over 2 years
      Did you got the answer?
  • Admin
    Admin over 7 years
    Nope still returning html
  • Muhammed Imran Hussain
    Muhammed Imran Hussain over 7 years
    I am sorry. You modified your question later so I missed the term "Unexpected token".
  • Brendan Metcalfe
    Brendan Metcalfe about 4 years
    Accept: application/json is key
  • FVBn
    FVBn over 3 years
    If that happens, what should we do ?
  • Ashir Mehmood
    Ashir Mehmood over 2 years
    That was exactly my case