"SyntaxError: Unexpected token < in JSON at position 0"
This ended up being a permissions problem for me. I was trying to access a url I didn't have authorization for with cancan, so the url was switched to users/sign_in
. the redirected url responds to html, not json. The first character in a html response is <
.
You're receiving HTML (or XML) back from the server, but the dataType: json
is telling jQuery to parse as JSON. Check the "Network" tab in Chrome dev tools to see contents of the server's response.
SyntaxError: Unexpected token < in JSON at position 0
You are getting an HTML file (or XML) instead of json.
Html files begin with <!DOCTYPE html>
.
I "achieved" this error by forgetting the https://
in my fetch
method:
fetch(`/api.github.com/users/${login}`)
.then(response => response.json())
.then(setData);
I verified my hunch:
I logged the response as text instead of JSON.
fetch(`/api.github.com/users/${login}`)
.then(response => response.text())
.then(text => console.log(text))
.then(setData);
Yep, an html file.
Solution:
I fixed the error by adding back the https://
in my fetch
method.
fetch(`https://api.github.com/users/${login}`)
.then(response => response.json())
.then(setData)
.catch(error => (console.log(error)));
The wording of the error message corresponds to what you get from Google Chrome when you run JSON.parse('<...')
. I know you said the server is setting Content-Type:application/json
, but I am led to believe the response body is actually HTML.
Feed.js:94 undefined "parsererror" "SyntaxError: Unexpected token < in JSON at position 0"
with the line
console.error(this.props.url, status, err.toString())
underlined.
The err
was actually thrown within jQuery
, and passed to you as a variable err
. The reason that line is underlined is simply because that is where you are logging it.
I would suggest that you add to your logging. Looking at the actual xhr
(XMLHttpRequest) properties to learn more about the response. Try adding console.warn(xhr.responseText)
and you will most likely see the HTML that is being received.