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
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 :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With