graphql - 使用 "operationName"和 "variables"向 apollo 服务器发送 POST 请求

标签 graphql apollo graphql-js apollo-server

我关注这个文档 https://www.apollographql.com/docs/apollo-server/requests.html#postRequests并尝试向 apollo 服务器发送 POST 请求。

测试代码:

it('should get author correctly', () => {
    const body = {
      query: `
        query {
          getAuthor($id: Int!) {
            name
          }
        }
      `,
      // operationName: 'query author',
      variables: {
        id: 1
      }
    };
    return rp.post(body).then(res => {
      expect(res.data.getAuthor.name).to.equal('lin');
    });
  });

rp.js:

const requestPromise = require('request-promise');
const { PORT } = require('./config');

const GRAPHQL_ENDPOINT = `http://localhost:${PORT}/graphql`;

function rp(options) {
  function post(body) {
    return requestPromise(GRAPHQL_ENDPOINT, {
      method: 'POST',
      body,
      json: true,
      headers: {
        'Content-Type': 'application/json'
      }
    });
  }

  return {
    post
  };
}

module.exports = rp;

当我运行 npm test 命令时,出现错误:

graphql test suites
Go to http://localhost:3000/graphiql to run queries!
    ✓ t0
    1) should get author correctly


  1 passing (79ms)
  1 failing

  1) graphql test suites
       should get author correctly:
     StatusCodeError: 400 - {"errors":[{"message":"Syntax Error: Expected Name, found $","locations":[{"line":3,"column":21}]}]}
      at new StatusCodeError (node_modules/request-promise-core/lib/errors.js:32:15)
      at Request.plumbing.callback (node_modules/request-promise-core/lib/plumbing.js:104:33)
      at Request.RP$callback [as _callback] (node_modules/request-promise-core/lib/plumbing.js:46:31)
      at Request.self.callback (node_modules/request/request.js:186:22)
      at Request.<anonymous> (node_modules/request/request.js:1163:10)
      at IncomingMessage.<anonymous> (node_modules/request/request.js:1085:12)
      at endReadableNT (_stream_readable.js:1106:12)
      at process._tickCallback (internal/process/next_tick.js:178:19)

最佳答案

您的查询格式无效。其实有两件事是错误的。第一,变量在操作的最顶部定义(在 querymutation 关键字旁边)。第二,如果定义了变量,则必须使用它。所以你的查询应该看起来更像这样:

query($id: Int!) {
  getAuthor(id: $id) {
    name
  }
}

关于graphql - 使用 "operationName"和 "variables"向 apollo 服务器发送 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49913447/

相关文章:

javascript - 将 graphql 查询与订阅相结合

javascript - 管理对同一个 Apollo 突变的多次调用

javascript - Apollo Query 组件如何使用它的自身值作为回调

graphql - 在我的查询中,我可以使用参数的结果来获取该查询中的更多信息吗?

graphql - 为什么 GraphQL `implements` 需要重复字段,这是强制性的吗?如果有,其根本原因是什么?

typescript - 如何在没有Webpack的 typescript 节点项目中使用.graphql

django - 查询 GraphQL 中的枚举值

javascript - 由于 id 冲突,Relay QueryRendererfragmentContainer 传递的 props 与服务器响应不同

reactjs - 如何重置 Apollo Client 的 useMutation 钩子(Hook)

node.js - GraphQLJS 使用 .graphql 文件从 NodeJS 进行查询