React: Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0

Hey I’m having trouble reading local data, I’ve become used to using APIs, I’ve made a mistake and not sure where. The error is:

Unhandled Rejection (SyntaxError): Unexpected token <; in JSON at position 0

I’ve checked the formatting of the json file.
Looking at devtools I can see that when it is doing the fetch it is bringing back index.html for some reason?

  componentDidMount = () => {
    let cities = "/api/cities";
      .then(resp => resp.json())
      .then(cities => this.setState({ cities }));

I don’t think this is an issue with componentDidMount but on the chance I’m wrong… When I’ve attached fetch requests to form buttons and forget to set in the event handler it can cause the fetch to return the index route instead of whatever route I’d intended.

I think I would try moving this fetch to the class constructor & set state initially from there to see if the problem remains. I know immediately setting state in componentDidMount will trigger a re-render, but I don’t think it would trigger another request so I don’t know.

@react Can you provide the full url of the api request? Do you have your project on GitHub, so we can take a look?

thanks Randell! I’m giving up for now and just building a backend instead of a local database, because I’ve got strict time constraints on this. But I’ll come back to it again after.

This is almost always due to returning some sort of HTTP error in HTML format, i.e. the response starts with <DOCTYPE html> and so on. As soon as .json() tries to parse that first <, it throws an error.

Try replacing the first then with resp => console.log(resp) and you’ll be able to see what the HTTP error is.