Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Network error: Unexpected token < in JSON at position 0 at new ApolloError

enter image description here

const httpLink = createHttpLink({
  uri: 'http://localhost:3090/'
})

const client = new ApolloClient({
  link: httpLink,
  cache: new InMemoryCache()
})

client.query({
  query: gql`
    query users {
        email
    }
  `,
})
  .then(data => console.log(data))
  .catch(error => console.error(error));

This query gives an error when fetching from client-side code but when i execute this query in browser on http://localhost:3090/graphql it fetches data correctly

like image 307
Mukesh Kumar Avatar asked Nov 08 '18 14:11

Mukesh Kumar


People also ask

How do I fix unexpected token in JSON error?

The "Unexpected token u in JSON at position 0" error occurs when we pass an undefined value to the JSON. parse or $. parseJSON methods. To solve the error, inspect the value you're trying to parse and make sure it's a valid JSON string before parsing it.

What is unexpected token E in JSON at position 0?

Re: Unexpected token in JSON at position 0 This usually means that an error has been returned and that's not valid JSON. Check the browser developer tools console and network tabs. Turn on Debugging and (after reproducing the error) check the web server error logs.

What is Apollo boost?

Apollo Boost is a zero-config way to start using Apollo Client. It includes some sensible defaults, such as our recommended InMemoryCache and HttpLink , which come configured for you with our recommended settings.


2 Answers

The graphql endpoint you are posting your queries to is missing the /graphql. So your server probably returns an html document containing the 404 error message that starts with < from <html.... Apollo tries to parse that as the query result and fails to do so.

Check that httpLink is actually localhost:3090/graphql.

Also the syntax of a query is either:

{
    users {
        email
    }
}

or if you want to name the query:

query Users {
    users {
        email
    }
}
like image 141
trixn Avatar answered Oct 15 '22 08:10

trixn


For posterity in case someone finds this in the future, another reason you might get this error is if your API is returning something other than JSON. https://medium.com/programmers-developers/one-simple-apollo-client-debugging-tip-youll-like-7877a97b9c16

I ran into this issue because the content type that was being returned from my API was text/plain rather than application/json. Apollo lets you specify a different body serializer in this case. https://www.apollographql.com/docs/link/links/rest/

like image 24
Joyce Lee Avatar answered Oct 15 '22 09:10

Joyce Lee