如何在NestJS服务端为Apollo Client配置代理访问API
配置Apollo Client通过代理访问SpaceX GraphQL API
下面是几种可行的解决方案,根据你的运行环境选择:
方案1:修改Apollo Client地址 + 反向代理服务器配置
这种方式适合你有自己的代理服务器(比如Nginx、Express)的场景,通过代理服务器转发请求到目标API。
步骤1:调整Apollo Client的请求地址
修改Resolver中的Apollo Client初始化代码,将uri改为代理服务器的地址(假设代理服务器配置了/spacex-graphql路径转发到目标API):
@Resolver() export class LaunchResolver { private readonly client: ApolloClient<any>; constructor() { this.client = new ApolloClient({ uri: 'http://abc.xyz.com:8000/spacex-graphql', // 代理地址 cache: new InMemoryCache(), }); } // ... 其余代码保持不变 }
步骤2:配置代理服务器转发规则
如果用Express + http-proxy-middleware实现代理,代码如下:
const express = require('express'); const { createProxyMiddleware } = require('http-proxy-middleware'); const app = express(); // 配置代理转发 app.use('/spacex-graphql', createProxyMiddleware({ target: 'https://spacex-production.up.railway.app', changeOrigin: true, // 必须设置,确保目标服务器接收正确的Host头 pathRewrite: { '^/spacex-graphql': '/graphql' // 将代理路径重写为目标API的实际路径 } })); app.listen(8000, () => { console.log('代理服务器运行在8000端口'); });
如果用Nginx配置代理,在nginx.conf中添加:
server { listen 8000; server_name abc.xyz.com; location /spacex-graphql { proxy_pass https://spacex-production.up.railway.app/graphql; proxy_set_header Host spacex-production.up.railway.app; proxy_set_header X-Real-IP $remote_addr; } }
方案2:Node.js环境下直接通过代理发送请求
如果你的Resolver运行在Node.js环境(比如作为Apollo Server的一部分),可以直接在Apollo Client中配置代理请求,无需额外的代理服务器。
步骤1:安装依赖
npm install node-fetch https-proxy-agent
步骤2:修改Resolver代码
自定义Apollo Client的fetch函数,通过代理发送请求:
import fetch from 'node-fetch'; import { HttpsProxyAgent } from 'https-proxy-agent'; import { Resolver, Query } from '@nestjs/graphql'; import { ApolloClient, InMemoryCache, gql } from '@apollo/client'; @Resolver() export class LaunchResolver { private readonly client: ApolloClient<any>; constructor() { // 初始化代理Agent const proxyAgent = new HttpsProxyAgent('http://abc.xyz.com:8000'); this.client = new ApolloClient({ uri: 'https://spacex-production.up.railway.app/graphql', cache: new InMemoryCache(), // 自定义fetch,添加代理 fetch: (url, options) => fetch(url, { ...options, agent: proxyAgent }) }); } @Query('launches') async getLaunches(): Promise<any[]> { const response = await this.client.query({ query: gql` query GetLaunches { launches { mission_name launch_date_utc } } `, }); return response.data.launches; } }
如果代理需要用户名密码认证,修改代理地址为:
const proxyAgent = new HttpsProxyAgent('http://username:password@abc.xyz.com:8000');
方案3:前端开发环境代理(React/Vue)
如果这个Resolver是前端客户端代码,可通过开发环境代理配置实现,避免跨域问题的同时通过代理访问API。
以React为例,在项目根目录创建src/setupProxy.js:
const { createProxyMiddleware } = require('http-proxy-middleware'); module.exports = function(app) { app.use( '/spacex-graphql', createProxyMiddleware({ target: 'https://spacex-production.up.railway.app', changeOrigin: true, pathRewrite: { '^/spacex-graphql': '/graphql' } }) ); };
然后修改Apollo Client的uri为相对路径:
this.client = new ApolloClient({ uri: '/spacex-graphql', cache: new InMemoryCache(), });
注意事项
- 确保代理服务器允许转发到目标API,无防火墙或跨域限制
- HTTPS代理需使用
HttpsProxyAgent,HTTP代理使用HttpProxyAgent - 生产环境部署时,需确保代理配置生效(比如Nginx反向代理)
内容的提问来源于stack exchange,提问作者Krish909
相关产品推荐
相关产品推荐

