GraphQL请求调试之代理抓包

GraphQL请求调试之代理抓包

Tags
global-agent
代理
GraphQL
description
在GraphQL中如何调试node发送给后端接口的数据
更新时间
Last updated January 26, 2022

背景

 
由于GraphQL发送给RESTful接口的请求是由node发送的,我们无法直接查看,所以在发送一些较为复杂的请求,例如带有特定头部的请求,文件上传时,调试较为麻烦,可能缺少了什么参数但是就是无法看到。
此时我们就需要一个工具帮我们拦截到node发送出去的请求,我首先想到的是Apollo是否提供了方法让我们能够查看Server发出去的请求,但是没找到,所以自然我们就想到用抓包工具去抓包调试。简单直接。
我们可以使用老牌的抓包工具比如wireshark或者charles去做,我搜了一下发现一个叫proxyman的抓包工具,颜值比上面的都高,所谓颜值就是战斗力,所以我试用了一下这个工具来抓包
 

Proxyman

傻瓜式安装
 

安装证书

需要安装证书来拦截HTTPS请求
notion image
notion image
 
 

Global-Agent

接下来我们需要让Apollo Server的请求经过Proxyman,这样才能抓取到相应的请求
notion image
一开始我的想法是从openapi-to-graphql 入手,毕竟他们是最后生成请求代码的地方,但是并没有找到相关配置,最后在Apollo Server 的文档中找到了相应的办法 。
里面推荐使用global-agent作为代理配置的库,来帮助我们减少配置代码
 

使用方法

global-agent的使用方法非常简单,只需要在Apollo Server服务启动前调用bootstrapGlobalAgent
const { ApolloServer, gql } = require('apollo-server'); const { bootstrap: bootstrapGlobalAgent } = require('global-agent'); // Setup global support for environment variable based proxy configuration. bootstrapGlobalAgent(); // The following represents existing configuration, though its // important to bootstrap the agent before Apollo Server. const server = new ApolloServer({ typesDefs, resolvers, });
 
然后在启动node前设置好环境变量就行
$ GLOBAL_AGENT_HTTP_PROXY=http://proxy:3128/ node index.js
对应我们项目的代码就是
GLOBAL_AGENT_HTTP_PROXY=http://[你的ip]:9091/ yarn dev
这样就能让Apollo Server 的请求都经过Proxyman
 

筛选域名

然后我们可以通过左侧的筛选栏来筛选查看经过后端的请求
 
notion image
 
然后我们就可以查看headerbody 中究竟发了什么,缺了什么。
 

GraphQL

 
proxyman对客户端发出的GraphQL请求有更多的兼容,比如可以直接看到经过美化的GraphQL的请求文本,可以看到QueryName
notion image