Apollo 服务器重置 CORS 选项

Apollo Server resetting CORS options

A​​pollo 服务器忽略我的 CORS 层并应用它自己的选项。

尽管使用选项 设置 CORS 中间件以使用以下代码反映 来源:

    var corsOptions = {
       origin: true,  //This will just copy the request origin and put it in response
       optionsSuccessStatus: 200, 
       credentials: true, 
    };
    app.use(cors(corsOptions));

    const apolloServer = new ApolloServer({ schema, context , playground: true}); 
    await apolloServer.start();

   //Integrate with express
   apolloServer.applyMiddleware({app, path: '/api/graphql', cors: corsOptions});

A​​pollo 服务器忽略了我的 CORS 层和 returns 'Access-Control-Allow-Origin' : "\*",因此我收到了 CORS 错误,因为:

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'.

要解决此问题,您需要直接在 applyMiddleware 方法中提供 CORS 选项。 像这样:

var corsOptions = {
           origin: true,  //This will just copy the request origin and put it in response
           optionsSuccessStatus: 200, 
           credentials: true, 
        };
apolloServer.applyMiddleware({app, path: '/api/graphql', cors: corsOptions}); //WE ADDED CORS HERE

这里是 link 对同样问题的堆栈溢出讨论。

此外,如果有兴趣,offical documentation 会说以下内容。