【问题标题】:How to do a rest post request using apollo client?如何使用 apollo 客户端进行休息发布请求?
【发布时间】:2021-08-23 20:57:54
【问题描述】:

我知道我们也可以使用 apollo 执行休息请求,但我不知道如何执行发布请求,有人可以帮我吗?

我的 REST 发布请求端点是:<url>/transaction/getbyhash

有效载荷:

{"hash":"4e23f9e1d1729996de46fc94d28475b4614f101d72a98f221493f900dc33e0c2"}

有人可以帮我使用 apollo 客户端和 graphql-tag 编写相同的请求吗?

【问题讨论】:

    标签: rest apollo apollo-client react-apollo apollo-server


    【解决方案1】:

    您可以使用apollo-link-rest 在您的 GraphQL 查询中调用 REST API。

    例如

    rest-api-server.ts:

    import express from 'express';
    import faker from 'faker';
    
    const app = express();
    const port = 3000;
    
    app.use(express.json());
    app.post('/api/transaction/getbyhash', (req, res) => {
      console.log(req.body);
      res.json({
        email: faker.internet.email(),
        name: faker.name.findName(),
      });
    });
    
    app.listen(port, () => console.log(`HTTP server is listening on http://localhost:${port}`));
    

    client.ts:

    import { ApolloClient } from 'apollo-client';
    import { RestLink } from 'apollo-link-rest';
    import { InMemoryCache } from 'apollo-cache-inmemory';
    import gql from 'graphql-tag';
    import fetch from 'isomorphic-fetch';
    
    const restLink = new RestLink({
      uri: 'http://localhost:3000/api/',
      customFetch: fetch,
      headers: {
        'Content-Type': 'application/json',
      },
    });
    
    const client = new ApolloClient({
      cache: new InMemoryCache(),
      link: restLink,
    });
    
    const getbyhashQuery = gql`
      fragment Payload on REST {
        hash: String
      }
      query Me($input: Payload!) {
        person(input: $input) @rest(type: "Person", method: "POST", path: "transaction/getbyhash") {
          email
          name
        }
      }
    `;
    const payload = { hash: '4e23f9e1d1729996de46fc94d28475b4614f101d72a98f221493f900dc33e0c2' };
    
    client.query({ query: getbyhashQuery, variables: { input: payload } }).then((res) => {
      console.log(res.data);
    });
    

    日志:

    {
      person: {
        email: 'Bryce34@gmail.com',
        name: 'Miss Jaren Senger',
        __typename: 'Person'
      }
    }
    

    软件包版本:

    "apollo-cache-inmemory": "^1.6.6",
    "apollo-client": "^2.6.10",
    "apollo-link": "^1.2.14",
    "apollo-link-rest": "^0.7.3",
    "graphql-anywhere": "^4.2.7",
    "graphql": "^14.6.0",
    "isomorphic-fetch": "^3.0.0",
    

    【讨论】:

    • 非常感谢。我对 apollo-link-rest 文档感到非常困惑。我进入了突变。但是你节省了我的时间,伙计。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-18
    • 2019-12-26
    • 2011-07-07
    • 2021-02-24
    • 2019-08-19
    • 2019-07-06
    • 2017-02-21
    相关资源
    最近更新 更多