Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-apollo Error: Network error: Unexpected token < in JSON at position 1

I want to send a request to this server via Apollo and get a query :

const client = new ApolloClient({ link: new HttpLink({ uri:'http://mfapat.com/graphql/mfaapp/'}), cache: new InMemoryCache()
})

const FeedQuery = gql query{ allFmr{ fmrId, name, studio, bedRm1, bedRm2, bedRm3, bedRm4 } } ` But I'm facing this error message:

Unhandled (in react-apollo:Apollo(FMRScreen)) Error: Network error: Unexpected token < in JSON at position 1

at new ApolloError (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:109336:32)
at ObservableQuery.currentResult (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:109447:28)
at GraphQL.dataForChild (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:103192:66)
at GraphQL.render (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:103243:37)

....

But I can easily open "http://mfapat.com/graphql/mfaapp/" in my browser and get a query. Does anyone know where the problem is?

like image 674
Robinia Avatar asked Dec 23 '17 06:12

Robinia


Video Answer


2 Answers

Right now, Apollo treats everything sent from the server as JSON. However, if there is an error, then your server might be sending HTML to show a basic error page.

To see the error, open your dev tools, and look at the network tab. This shows an example 401 error:

401 error in dev tools

As you can see, if you were to parse this as JSON you would stumble over the first character: < which is where our error message comes from.

Reading the specific error sent enables you to fix the bug.

To fix the general error, configure your server to send JSON on HTTP errors, not HTML code. This should allow Apollo to parse it and display a sensible error page.

EDIT: Also see this discussion - hopefully they will change the default Apollo behavior, or at least provide useful discussion.

like image 67
eedrah Avatar answered Oct 16 '22 23:10

eedrah


Base on @eedrah answer, I managed to resolve this issue by using an error handler middleware to always return erros as JSONs, so that Apollo Client error link can parse the errors. // On Apollo server // Error handler const errorHandler = (err, req, res, next) => { if (res.headersSent) { return next(err); } const { status } = err; res.status(status).json(err); }; app.use(errorHandler);

like image 37
sonlexqt Avatar answered Oct 17 '22 00:10

sonlexqt