question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[Solved] apollo-server-express cors not handling

See original GitHub issue

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

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:6

github_iconTop GitHub Comments

6reactions
ghostcommented, Apr 10, 2020

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/

0reactions
Ptrip9199commented, Apr 10, 2020

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.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Configuring CORS - Apollo GraphQL Docs
You can enable credentials with CORS by setting the Access-Control-Allow-Credentials HTTP header to true . You must specify an origin to enable credentialed ......
Read more >
apollo-server-express CORS issue - node.js - Stack Overflow
With apollo-server-express 1.3.6 I was doing the following without no issues: app.use( '/graphql', graphqlUploadExpress({ ...
Read more >
Enabling CORS for Express-GraphQL & Apollo Server - Prisma
Frontend. The problem is that neither express-graphql nor apollo-server accept HTTP requests other than GET and POST — which is why the request ......
Read more >
CORS in Apollo Client & Apollo Server - DEV Community ‍ ‍
The Solution · Using the package apollo-server-express and the cors middleware. · Disabling the Apollo Server cors to avoid conflicts.
Read more >
Solving CORS Errors Associated with Deploying a Node.js + ...
We will use Apollo Server for our GraphQL server, Typeorm to handle Postgres functions, Express-Session for sessions and cookies, and Redis to ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found