2022年如何通过Apollo Server Express正常打开GraphQL Playground页面?
解决GraphQL Playground无法正常加载的问题
问题原因
Apollo Server从v3版本开始,默认不再内置GraphQL Playground,转而使用Apollo Sandbox作为调试工具。你遇到的“无法加载完整着陆页面;你似乎处于离线状态”提示,要么是因为默认的Sandbox加载需要网络访问外部资源,要么是你仍想使用传统Playground但未配置相关选项。
解决方案
方案1:使用官方默认的Apollo Sandbox(推荐)
Apollo Sandbox是Playground的替代工具,功能更全面,默认在v3+版本中启用。确保你的代码开启了introspection(开发环境默认开启),直接访问http://localhost:8080/graphql即可加载Sandbox。若需显式配置,可修改ApolloServer初始化代码:
const server = new ApolloServer({ typeDefs, resolvers, introspection: true, // 开发环境必须开启,否则Sandbox无法获取Schema sandbox: true // 默认值为true,可省略 });
方案2:手动配置启用传统GraphQL Playground
如果坚持使用旧版Playground,需要单独安装依赖并挂载路由:
- 安装依赖包:
npm install graphql-playground-middleware-express --save
- 修改项目代码:
const express = require('express'); const { ApolloServer, gql } = require('apollo-server-express'); // 引入Playground中间件 const { expressPlayground } = require('graphql-playground-middleware-express'); const typeDefs = gql` type Query { hello: String } `; const resolvers = { Query: { hello: () => 'Hello world!', }, }; const server = new ApolloServer({ typeDefs, resolvers }); const app = express(); server.applyMiddleware({ app }); // 挂载Playground到自定义路由 app.get('/playground', expressPlayground({ endpoint: '/graphql' })); const port = 8080; app.listen({ port }, () => { console.log(`🚀 Server ready at http://localhost:${port}${server.graphqlPath}`); console.log(`📋 Playground ready at http://localhost:${port}/playground`); });
启动项目后访问http://localhost:8080/playground即可打开传统Playground界面。
方案3:排查网络与环境问题
如果使用的是Apollo Server v2版本(Playground默认启用),出现离线提示大概率是网络无法加载Playground的静态资源。可尝试切换网络环境,或检查本地代理设置是否拦截了相关请求。
内容的提问来源于stack exchange,提问作者Mohan Srinivas
相关产品推荐
相关产品推荐

