Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I always get a cors error that wildcard * is not allowed, although I specified a origin on the server?

I created a simple graphQL Chat with Apollo Server and Apollo Client.

It also uses session cookies so I initialized the server with the npm package cors like this:

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

On the client side I use apollo client and create a http link like this:

const httpLink = new HttpLink({
  uri: "http://localhost:4000/graphql",
  credentials: "include"
});

So I include credentials and the server has the origin of my client (which is indeed http://localhost:3000 - create-react-app default).

When I want to run a query I get this error in my browser console:

Access to fetch at 'http://localhost:4000/graphql' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

Why does it say that the response header has a wildcard * set, but on cors I set a specific origin, so it should not be a wildcard right?

What am I missing here guys? I also restarted both servers of course.

When I set the client like this:

const httpLink = new HttpLink({
  uri: "http://localhost:4000/graphql",
  credentials: "same-origin"
});

I don't get an error message from cors, but I don't receive a cookie from the server. Cookies work because on graphQL Playground everything works as expected.

If you want to see the full code: https://github.com/SelfDevTV/graphql-simple-chat

like image 972
GeraltDieSocke Avatar asked Jul 09 '19 13:07

GeraltDieSocke


2 Answers

The problem is solved.

In my index.js file from the server. A few lines below I apply the express app as a middleware to the apollo server instance like so:

server.applyMiddleware({ app });

But this overrides cors options I set above.

So I have to call it like this: server.applyMiddleware({ app, cors: false });

Now everything works perfectly :)

like image 179
GeraltDieSocke Avatar answered Nov 15 '22 11:11

GeraltDieSocke


You can instead tell the Apollo server how to configure cors.

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

server.applyMiddleware({
  app,
  cors: corsOptions
}) 

Then you can eliminate the express cors middleware entirely.

like image 21
Spenser Saling Avatar answered Nov 15 '22 09:11

Spenser Saling