Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apollo client query error: "Network error: Failed to fetch" How to troubleshoot?

An Apollo server is setup, and it responds correctly to the query when using graphiql.

An existing react-redux app with server side rendering needs to start using graphql and make this query.

A component of this app has been setup to do the same query, it seems to be doing the network request, but it fails with Error: {"graphQLErrors":[],"networkError":{},"message":"Network error: Failed to fetch"}

Any troubleshooting advice?

like image 726
Johnny5 Avatar asked Mar 20 '18 21:03

Johnny5


3 Answers

It really is cors issue. I tried to fix it by using express. But it didn't work with Apollo GraphQL.

const corsOptions = {
    origin: "http://localhost:3000",
    credentials: true
  };
app.use(cors(corsOptions));

So, I tried configuring cors inside GraphQL server and It Worked.

For Apollo Server

const corsOptions = {
    origin: "http://localhost:3000",
    credentials: true
  };

const server = new ApolloServer({
  typeDefs,
  resolvers,
  cors: corsOptions
});

server.listen().then(({ url }) => {
  console.log(`🚀 Server ready at ${url}`);
});

For GraphQL Yoga

const options = {
  cors: corsOptions
};

server.start(options, () =>
  console.log("Server is running on http://localhost:4000")
);
like image 197
l3lackcurtains Avatar answered Sep 18 '22 11:09

l3lackcurtains


I was running apollo client on localhost, and apollo server on someDomain.com, so it was a CORS issue. After loading the page that does the query in chrome incognito mode and refreshing, this error was found in the chrome dev tools console:

httpLink.js:71 OPTIONS https://someDomain.com/graphql 405 (Method Not Allowed) (anonymous) @ httpLink.js:71 ... (index):1 Failed to load https://someDomain.com/graphql: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:8443' is therefore not allowed access. The response had HTTP status code 405. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

A quick fix for this (test only) setup was to setup cors on the express apollo server like this post suggests. https://blog.graph.cool/enabling-cors-for-express-graphql-apollo-server-1ef999bfb38d

like image 30
Johnny5 Avatar answered Sep 17 '22 11:09

Johnny5


All you need to do to make the following work is to enable cors library for your Apollo-Graphql server

yarn add cors / npm install cors

Now got to you app.js or server.js ( Basically the entry file of your server )

add the following lines to it

const cors = require('cors');

app.use(cors()); // Make sure you have express initialised before this.

like image 28
Cherag Verma Avatar answered Sep 18 '22 11:09

Cherag Verma