本地Azure Functions搭建GraphQL API遇沙箱嵌入及CORS问题求助
解决本地Azure Functions中Apollo GraphQL API的访问错误与GraphiQL问题
针对你遇到的本地Azure Functions部署Apollo GraphQL API后,直接访问端点报错、GraphiQL无法正常加载的问题,可按以下步骤排查解决:
1. 修正CORS配置范围
当前代码中CORS仅允许http://localhost:7071,但Apollo沙箱或直接访问时的跨域请求可能来自其他域名,测试阶段可放宽CORS限制:
import { ApolloServer, gql } from "apollo-server-azure-functions" const typeDefs = gql` type Query { graphQlOnAzure: String! } ` const resolvers = { Query: { graphQlOnAzure() { return "GraphQL on Azure!"; } } } const server = new ApolloServer({ typeDefs, resolvers}) export default server.createHandler({ cors: { origin: '*', // 测试环境允许所有来源,生产环境按需限制 credentials: true, methods: ['POST', 'GET'], // 覆盖GraphQL所需请求方法 allowedHeaders: ['Content-Type', 'Authorization'] } });
2. 补充Azure Functions本地CORS配置
除了代码中的配置,还需在local.settings.json中设置全局CORS规则,修改后重启本地函数服务:
{ "IsEncrypted": false, "Values": { "AzureWebJobsStorage": "", "FUNCTIONS_WORKER_RUNTIME": "node" }, "Host": { "CORS": "*", "CORSCredentials": true } }
3. 启用GraphiQL/Apollo Studio界面
默认情况下apollo-server-azure-functions可能未开启可视化查询界面,需在ApolloServer配置中显式启用:
- 若使用旧版Apollo Server(v2/v3),启用Playground:
const server = new ApolloServer({ typeDefs, resolvers, playground: true, // 开启GraphiQL界面 introspection: true // 允许Schema自省,沙箱依赖此配置 });
- 若使用新版Apollo Server(v4+),启用Apollo Studio沙箱:
const server = new ApolloServer({ typeDefs, resolvers, studio: true, // 开启Apollo Studio沙箱 introspection: true });
4. 确认端点访问地址正确性
本地Azure Functions的GraphQL端点格式为http://localhost:7071/api/<你的函数名称>,确保你访问的URL与函数名一致(比如函数名为graphql,则地址是http://localhost:7071/api/graphql)。
5. 测试API可用性
用Postman或curl发送POST请求验证API本身是否正常:
- 请求URL:
http://localhost:7071/api/<你的函数名> - 请求体(JSON格式):
{ "query": "{ graphQlOnAzure }" }
若返回{"data":{"graphQlOnAzure":"GraphQL on Azure!"}},说明API核心功能正常,问题集中在跨域或可视化界面配置上。
内容的提问来源于stack exchange,提问作者Sumchans
相关产品推荐
相关产品推荐

