Apollo-server: [Solved] apollo-server-express cors not handling

Created on 2 Oct 2019  路  6Comments  路  Source: apollographql/apollo-server

Problem Kept receiving cors errors with many possible configurations

Solution Ensure that when you instantiate your Apollo Client at the root that it points to the correct URI

Instead of:

// Pass along GraphQL endpoint to URI
const client = new ApolloClient({
    uri: 'http://localhost:5000/graphql'
});

I was using

// Pass along GraphQL endpoint to URI
const client = new ApolloClient({
    uri: 'https://localhost:5000/graphql'
});

There was no issue with the apollo server or express.
The classic "bug between my ears"

~~

Original Post below

Package: apollo-server-express

Version: v2.9.4

Issue: CORS settings aren't taking effect (local dev)

Description:

From our client (localhost: 3000) we are executing a useMutation hook and receiving the following front-end console error:

[Network error]: TypeError: NetworkError when attempting to fetch resource.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:5000/graphql. (Reason: CORS request did not succeed).

However, we have followed guides on enabling cors for apollo on our server as follows:

import * as cors from 'cors';
import * as express from 'express';
import * as session from 'express-session';

import { ApolloServer } from 'apollo-server-express';
import { createConnection } from 'typeorm';
import { resolvers } from './resolvers';
import { typeDefs } from './typeDefs';

// Setup Apollo server importing our typeDefs and resolvers
const startServer = async () => {
    const server = new ApolloServer({
        typeDefs,
        resolvers,
        context: ({ req }: any) => ({ req })
    });

    // Start the express package & enable cors
    const app = express();

    const corsOptions = {
        origin: true,
        credentials: true
    };

    app.use(cors(corsOptions));

    // Pass in session auth middleware to express
    app.use(
        session({
            secret: `${process.env.SESSION_SECRET}`,
            resave: false, // Only resaves session w/ change
            saveUninitialized: false // Don't assign a user a session til we give them data
        })
    );

    // Asynchronously connect to our DB
    await createConnection();

    // Set relevant PORT
    const PORT = process.env.PORT || 5000;

    // Pass express in as the apollo middleware
    server.applyMiddleware({
        app,
        path: '/',
        cors: false
    });

    // Listen on the assigned port for new requests
    app.listen({ port: PORT }, () =>
        console.log(
            `馃殌  Server ready at http://localhost:${PORT}${server.graphqlPath} 馃殌`
        )
    );
};

// Start the server asynchrounously
startServer();

We have tried setting cors to false, true, and cors(corsOptions) directly in the Apply Middleware section. Having tried several configurations, it would appear that the CORS settings are not being propogated into the apollo-server.

We would love some insight or advice on this issue -- thank you!

3058 is not relevant as we do not have kubernetes at the moment

Most helpful comment

Are you disabling the cors middleware? It's been a few months, but if I recall, you can run into issues when there are two different libaries competing for CORS.

In my code, I'm explicitly passing in something like:

// Pass express in as the apollo middleware
    server.applyMiddleware({
        app,
        path: '/',
        cors: false
    });

to disable one of the CORS for one. There are a handful of documents online that might be useful to try with various configurations. So my recommendation would be to try "https" in the URI and use one of the methods to disable the competing CORS instance.

To start taking a look around.
https://ednsquare.com/story/how-to-enable-cors-for-express-graphql-apollo-server------ACJiD5

https://dev.to/doylecodes/cors-in-apollo-client-apollo-server-3cbj

https://www.apollographql.com/docs/react/networking/authentication/

All 6 comments

Did you find a solution @sethgoodluck?

@benbowler

Did you find a solution @sethgoodluck?

Yes, notice the URI above needs "https" instead of "http"

@sethgoodluck I tried with both "http" and "https", but still get the same CORS error. Anyone have a solution?

@Ptrip9199

Could you put your code here?
Will take a look and see if anything jumps out at me.

Yeah sure

const client = new ApolloClient({ uri:"http://localhost:5000/graphql" });

I am importing ApolloClient from 'apollo-boost' btw...
This is the client, I tried both http and https but to no success..
I am running the GraphQL server with flask.

Are you disabling the cors middleware? It's been a few months, but if I recall, you can run into issues when there are two different libaries competing for CORS.

In my code, I'm explicitly passing in something like:

// Pass express in as the apollo middleware
    server.applyMiddleware({
        app,
        path: '/',
        cors: false
    });

to disable one of the CORS for one. There are a handful of documents online that might be useful to try with various configurations. So my recommendation would be to try "https" in the URI and use one of the methods to disable the competing CORS instance.

To start taking a look around.
https://ednsquare.com/story/how-to-enable-cors-for-express-graphql-apollo-server------ACJiD5

https://dev.to/doylecodes/cors-in-apollo-client-apollo-server-3cbj

https://www.apollographql.com/docs/react/networking/authentication/

Was this page helpful?
0 / 5 - 0 ratings