The error “”SyntaxError: Unexpected token < in JSON at position 0” is an error that is invoked whenever you are coding in react.js and are trying to create a content feed. Given below is the snippet of the error:
SyntaxError: Unexpected token < in JSON at position 0
I would like to share with you the steps I took to fix the “”SyntaxError: Unexpected token < in JSON at position 0” in your project file.
Why SyntaxError Unexpected token < in JSON at position 0 Error is Seen?
The error, “”SyntaxError: Unexpected token < in JSON at position 0” is seen because; you are getting an HTML file (or XML) instead of json.
Html files always start with <!DOCTYPE html>
.
You can recreate this error by missing the https://
in your fetch
method:
fetch(`/api.github.com/users/${login}`)
.then(response => response.json())
.then(setData);
You can verify this by logging the response as text instead of JSON, as shown below:
fetch(`/api.github.com/users/${login}`)
.then(response => response.text())
.then(text => console.log(text))
.then(setData);
You may find the above-code is an HTML. If this is not the case then it is likely that your error is most likely due to a permission issue or an issue with the node modules.
The detailed solution to fix the error “”SyntaxError: Unexpected token < in JSON at position 0”, is given below:
How to fix SyntaxError Unexpected token < in JSON at position 0 Error?
To fix the error, you have to add back the https://
in your fetch
method. If the error still persists remove and re-install corrupt node-models.
To fix the error, “”SyntaxError: Unexpected token < in JSON at position 0”, you have to follow the below mentioned steps:
First, if you are getting an HTML instead of an json then, you have to add back the https://
in your fetch
method. :
fetch(`https://api.github.com/users/${login}`)
.then(response => response.json())
.then(setData)
.catch(error => (console.log(error)));
If the above step does not help to fix the error then it is likely that your error is caused due to corrupted node modules. You have to remove the corrupted node modules by following the code given below:
rm -rf node_modules
npm install
If you still face the error, then remove your package-lock.json, and it should work to fix the error.
This should fix the error, “”SyntaxError: Unexpected token < in JSON at position 0”.
Conclusion
To fix the error “”SyntaxError: Unexpected token < in JSON at position 0”, you have to add back the https://
in your fetch
method. If the error still persists remove and re-install corrupt node-models