Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

reactjs - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...