如果你在 Apollo Server 中设置了 CORS 选项,但发现它被重置了,可能是因为 Apollo Server 内部有一些逻辑会触发重置。为了解决这个问题,你需要在设置 CORS 选项时,将 Apollo Server 的默认选项与你的选项进行合并。
以下是一个示例代码:
const { ApolloServer } = require('apollo-server');
const express = require('express');
const cors = require('cors');
const typeDefs = ...; // 定义 GraphQL schema
const resolvers = ...; // 定义 resolver
const server = new ApolloServer({
typeDefs,
resolvers,
// 设置 CORS 选项
cors: {
origin: 'http://localhost:3000',
credentials: true,
},
context: ({ req, res }) => ({ req, res }),
});
// 创建 Express 应用程序
const app = express();
// 将用户指定的 CORS 选项与 Apollo Server 的默认选项进行合并
const corsOptions = {
...server._options.cors, // 获取 Apollo Server 的默认选项
origin: 'http://localhost:3000',
credentials: true,
};
// 启用 CORS
app.use(cors(corsOptions));
// 将 Apollo Server 与 Express 进行连接
server.applyMiddleware({ app });
// 启动服务器
app.listen({ port: 4000 }, () => {
console.log(`� Server ready at http://localhost:3000${server.graphqlPath}`);
});
在上面的示例代码中,server._options.cors
用于获取 Apollo Server 的默认 CORS 选项,然后将其与自己的选项进行合并。这样就可以确保设置的 CORS 选项不会被 Apollo Server 重置。