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
Comments
-
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 over 7 yearsplease try "Content-Type" : "text/plain"
-
G H Prakash over 2 yearsDid you got the answer?
-
-
Admin over 7 yearsNope still returning html
-
Muhammed Imran Hussain over 7 yearsI am sorry. You modified your question later so I missed the term "Unexpected token".
-
Brendan Metcalfe about 4 yearsAccept: application/json is key
-
FVBn over 3 yearsIf that happens, what should we do ?
-
Ashir Mehmood over 2 yearsThat was exactly my case