Johnny5
Johnny5

Reputation: 513

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?

Upvotes: 10

Views: 47079

Answers (5)

Johnny5
Johnny5

Reputation: 513

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

Upvotes: 3

chidalu okechukwu
chidalu okechukwu

Reputation: 27

Try using the cors middleware at the top of your code. This initializes the cross-origin resource sharing first before the graphql endpoint is created.

enter const { urlencoded } = require("express");
const express = require("express");
const app = express(); //create an express application
const helmet = require("helmet"); //require helment from node modules
const cors = require("cors"); //cross-origin-resource sharing
const mR = require("./routes/main");
const schema = require("./graph-schema/schema");
const mongoose = require("mongoose");

//cross-origin-resources-sharing defined at the top before your graphql endpoint
app.use(
  cors({
    optionsSuccessStatus: 200, //option sucess status
    origin: "http://localhost:3000", //origin allowed to access the server
  })
);

//connect to database
mongoose.connect("mongodb://localhost:27017/Graphql_tutorial", {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  useCreateIndex: true,
});

//graphql area
const { graphqlHTTP } = require("express-graphql"); //This allows express to understand graphql and lunch its api.

app.use(
  "/graphql",
  graphqlHTTP({
    schema,
    graphiql: true,
  })
);//code here

Upvotes: 0

Cherag Verma
Cherag Verma

Reputation: 299

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.

Upvotes: 2

2Fwebd
2Fwebd

Reputation: 2095

You can have this error as well if you pass a null HEADER in your request through Apollo, so something like:

const middlewareLink = setContext(() => ({
    headers: {
        'authorization': `Bearer ${FeedierExchanger.token}` || null
    }
}));

Change it to:

const middlewareLink = setContext(() => ({
    headers: {
        'authorization': `Bearer ${FeedierExchanger.token}` || ''
    }
}));

Or remove this part:

|| ''

If you've the correct backend validation.

Upvotes: 0

l3lackcurtains
l3lackcurtains

Reputation: 162

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")
);

Upvotes: 8

Related Questions