使用 Apollo Client 时,如何使用 GraphQL 获取 Postman Mock API 以成功匹配正文?

How do I get a Postman Mock API with GraphQL to successfully match the body when using the Apollo Client?

我想使用 Postman Mock API 来模拟 graphql 查询。当我从 Postman 中向 Postman Mock API 发送请求时,它工作得很好,但是,当我从我的 React 应用程序使用 Apollo Client 时,Postman Mock API 的响应说没有匹配的请求。

我在 Postman 调用 mock API 和 Apollo Client 调用 mock API.

这是我的 Postman Mock API 日志:

直接从 Postman 成功调用模拟 API 的正文负载(为简洁起见缩短):

{operationName: "getThings", variables: {}, query: "query getThings {
  things {
    id
    status
    __typename
  }
}"}

从 Apollo Client 调用模拟 API 失败的正文负载(为简洁起见缩短):

{operationName: "getThings", variables: {}, query: "query getThings {
  things {
    id
    status
    __typename
  }
}"}

这是我们从邮递员那里得到的回复

我也尝试过将 Postman 模拟 API 调用转换为仅具有 JSON GraphQL 请求主体的 REST API 调用,但这也没有用,我得到了相同的结果。

最后,Postman 论坛上的 this thread 似乎是同一个问题,但也没有解决任何问题。

有谁知道为什么Apollo客户端发送的请求体不匹配?

事实证明,我只是在点击邮递员模拟 API 时在我的 url 中输入错误...:facepalm:

但是,我应该指出的一件事是,在邮递员中匹配请求 body 时,您将不得不使用 raw 并复制从浏览器发送的有效负载由于最有可能从 Apollo 客户端发送的“operationName”,因此使用类型 GraphQL。 Postman GraphQL 负载似乎不允许您设置操作名称,因此 body 永远不会匹配,除非您在 JSON 请求中明确设置操作名称。

如果有人需要,这里是一步一步的:

  1. 像对任何其他请求一样,在 Postman GraphQL 端点上为模拟端点创建一个示例请求
  2. x-mock-match-request-body 设置为 true
  3. content-type header 设置为 application/json
  4. 将 body 设置为 raw 并键入 JSON
  5. 不要忘记 return __typename 因为 Apollo 客户端在每次请求时都会请求这个