代码之家  ›  专栏  ›  技术社区  ›  Lin Du Correcter

使用“operationName”和“variables”向阿波罗服务器发送POST请求

  •  2
  • Lin Du Correcter  · 技术社区  · 7 年前

    我遵循这个文件 https://www.apollographql.com/docs/apollo-server/requests.html#postRequests 并尝试发送 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)
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Daniel Rearden    7 年前

    查询的格式无效。实际上有两件事不对。首先,变量定义在操作的最顶端(在 query mutation 关键字)。第二,如果你定义了一个变量,你必须使用它。因此,您的查询应该更像这样:

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