NestJS v9 GraphQL Playground部署后显示“无法连接服务器”求助
解决NestJS GraphQL Playground部署到DigitalOcean后无法连接服务器的问题
核心问题分析
你遇到的情况是:正常查询/变更能执行,但Playground无法加载Schema和文档,说明Playground用于获取Schema的Introspection请求出了问题,而非普通请求的CORS或转发故障。下面是针对性的解决方案:
1. 修正GraphQL Playground的Endpoint协议
本地开发用HTTP,部署后切换到HTTPS,但Playground默认可能仍指向HTTP接口,导致请求被浏览器拦截。直接在GraphQL模块配置里指定HTTPS的Endpoint:
import { Module } from '@nestjs/common'; import { GraphQLModule } from '@nestjs/graphql'; import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo'; @Module({ imports: [ GraphQLModule.forRoot<ApolloDriverConfig>({ driver: ApolloDriver, autoSchemaFile: true, // 强制指定Playground的线上HTTPS地址 playground: { endpoint: 'https://api.my-live-server.io/graphql', settings: { 'request.credentials': 'include', }, }, // 把CORS配置移到GraphQL模块内,避免全局配置不生效 cors: { credentials: true, origin: ['http://localhost:3000', 'https://api.my-live-server.io'], }, }), ], }) export class AppModule {}
2. 修复Nginx配置的关键转发头部
Nginx如果没正确转发协议头部,NestJS会误以为请求是HTTP,导致Playground生成错误的接口地址。更新你的Nginx配置:
server { listen 443 ssl; server_name api.my-live-server.io; ssl_certificate /path/to/your/cert.pem; ssl_certificate_key /path/to/your/key.pem; location /graphql { proxy_pass http://localhost:3000; # 替换成你的NestJS服务端口 proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # 关键:告诉NestJS当前请求是HTTPS proxy_set_header X-Forwarded-Proto $scheme; proxy_cache_bypass $http_upgrade; # 处理OPTIONS预请求 if ($request_method = OPTIONS) { add_header Access-Control-Allow-Origin 'https://api.my-live-server.io'; add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS'; add_header Access-Control-Allow-Headers 'Content-Type, Authorization'; add_header Access-Control-Allow-Credentials 'true'; return 204; } add_header Access-Control-Allow-Origin 'https://api.my-live-server.io'; add_header Access-Control-Allow-Credentials 'true'; } }
配置更新后,重启Nginx:sudo systemctl restart nginx
3. 确保Introspection查询未被禁用
生产环境下如果不小心关闭了Introspection,Playground就无法获取Schema。检查GraphQL配置:
GraphQLModule.forRoot<ApolloDriverConfig>({ driver: ApolloDriver, autoSchemaFile: true, playground: true, // 确保生产环境也开启Introspection(如果需要使用Playground) introspection: process.env.NODE_ENV !== 'production' ? true : true, })
4. 清除浏览器缓存或使用无痕模式
浏览器缓存的旧Playground配置可能导致异常,尝试清除缓存后重新访问,或者直接用无痕模式打开Playground页面。
内容的提问来源于stack exchange,提问作者Nditah
相关产品推荐
相关产品推荐

