ApolloServer使用createAPIGatewayProxyEventV2RequestHandler如何配置CORS?
Apollo Server 4 + AWS Lambda 配置CORS跨域方案
问题背景
本地开发时前后端分离部署在不同端口,使用Apollo Server 4结合AWS Lambda时,找不到官方文档中Lambda端设置Access-Control-Allow-Origin等CORS头的方法,现有Lambda配置代码如下:
import { ApolloServer } from "@apollo/server"; import { startServerAndCreateLambdaHandler, handlers } from '@as-integrations/aws-lambda'; import typeDefs from "./schema.js" import resolvers from "./resolvers.js" import crypto from 'crypto' const getUser = (token) => { // security stuff } const production = process.env.NODE_ENV === 'production' const server = new ApolloServer({ typeDefs, resolvers, introspection: !production, playground: !production, debug: !production, context: ({ event: { headers } }) => { const token = headers.authorization || ''; const user = getUser(token); return { user }; }, }); const graphqlHandler = startServerAndCreateLambdaHandler( server, handlers.createAPIGatewayProxyEventV2RequestHandler(), ); export { graphqlHandler as handler }
解决方案
Apollo的AWS Lambda集成默认未内置CORS处理逻辑,可通过包装Lambda handler手动添加响应头,同时处理OPTIONS预检请求:
代码修改示例
// 保留原有的Apollo Server定义、getUser函数等代码不变 const graphqlHandler = startServerAndCreateLambdaHandler( server, handlers.createAPIGatewayProxyEventV2RequestHandler(), ); // 包装handler注入CORS头并处理OPTIONS请求 export const handler = async (event, context) => { // 先执行原Apollo handler获取响应 const response = await graphqlHandler(event, context); // 配置CORS头,根据环境切换允许的源 const allowedOrigin = process.env.NODE_ENV === 'production' ? 'https://your-production-domain.com' // 替换为生产环境客户端域名 : 'http://localhost:3000'; // 替换为本地客户端端口 const corsHeaders = { 'Access-Control-Allow-Origin': allowedOrigin, 'Access-Control-Allow-Methods': 'GET, POST, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type, Authorization', }; // 合并原有响应头与CORS头 response.headers = { ...response.headers, ...corsHeaders }; // 处理浏览器OPTIONS预检请求,直接返回200 if (event.requestContext.http.method === 'OPTIONS') { return { statusCode: 200, headers: corsHeaders, body: '', }; } return response; };
说明
- 针对本地开发和生产环境分别配置
allowedOrigin,避免生产环境开放过多权限 - 必须处理OPTIONS预检请求,否则浏览器会拦截跨域请求
- 若使用AWS API Gateway V2,也可直接在控制台配置CORS规则,但Lambda层面的配置更灵活(比如根据请求头动态调整允许的源)
内容的提问来源于stack exchange,提问作者Jeff Lowery
相关产品推荐
相关产品推荐

