Wednesday, 11 April, 2018 UTC


Summary

Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0
You made an HTTP request, probably with Fetch, and it blew up with this error.
Ugh.
Here’s what causes it and how to fix it.
The Cause
This happens when you make a request to the server and parse the response as JSON, but it’s not JSON. The code responsible might look something like this:
fetch('/users').then(res => res.json()) 
The actual request worked fine. It got a response. But the res.json() is what failed.
JSON should start with a valid JSON value – an object, array, string, number, or false/true/null. This response started with a < (hence the “Unexpected token <”).
That unexpected token, <, is a strong clue that the response was HTML instead of JSON.
The root cause is that the server returned HTML. Why would it do that?
The Fix
The server might return HTML instead of JSON for a bunch of reasons:
  • The URL doesn’t exist and the server returned an 404 page as HTML. You might have a typo in the client code (/users instead of /user) or in the server code that sets up the route.
  • The server might need a restart if you just added a URL to it. If you’re using an Express server for instance, and you just added a new app.get('/users', ...) route, but didn’t restart the server, then it doesn’t know about the new route yet.
  • The client’s proxy isn’t set up: if you’re using a Webpack dev server like Create React App, you can set up a proxy to forward requests to a backend server.
Also, check the browser devtools Network tab and look for the request that caused this error, and then look at the response that came back.
Is it a 404 page? (might be a missing route or a typo)
Is it the index.html page? (might be a missing route or a misconfigured proxy)
If everything looks fine, then restart your backend server and your frontend dev server, and see if the problem goes away.
Problem Solved?
Hopefully you’ve now gotten rid of the error. If not, leave a comment below with what you tried, and I’ll try to help.
Unexpected token < in JSON at position 0 was originally published by Dave Ceddia at Dave Ceddia on April 11, 2018.
CodeProject