【问题标题】:Using an alternative GraphQL client to connect to Apollo Server使用替代 GraphQL 客户端连接到 Apollo Server
【发布时间】:2020-04-27 20:46:07
【问题描述】:

是否可以使用非 Apollo 客户端(例如 graphql.js - https://github.com/f/graphql.js)连接到 Apollo GraphQL 服务器?

如果是这样,应该使用哪个端点?还是有其他方法?

这会失败并出现HTTP 500 服务器错误:

const graph = graphql('http://localhost:3013/graphql', {
        method: 'POST' // POST by default.
    });

    const res = graph(`query getQuestions {
        questions {
          id,
          question
        }
      }
    `);

    res().
        then((result) => console.log(result))
        .catch((err) => console.log(err));

【问题讨论】:

    标签: graphql apollo-client apollo-server


    【解决方案1】:

    当然,您可以使用任何 GraphQL 客户端,只要客户端遵循 GraphQL 规范即可。

    例如

    server.ts:

    import { ApolloServer, gql } from 'apollo-server';
    import graphql from 'graphql.js';
    
    const typeDefs = gql`
      type Query {
        _: String
      }
    `;
    const resolvers = {
      Query: {
        _: () => 'Hello',
      },
    };
    const server = new ApolloServer({
      typeDefs,
      resolvers,
    });
    server.listen().then(async ({ url }) => {
      console.log(`Apollo server is listening on ${url}graphql`);
      const graph = graphql(`${url}graphql`, { asJSON: true });
      const helloQuery = graph(`
        query {
          _
        }
      `);
      const actual = await helloQuery();
      console.log('actual: ', actual);
      server.stop();
    });
    

    输出:

    Apollo server is listening on http://localhost:4000/graphql
    actual:  { _: 'Hello' }
    

    【讨论】:

    • 我缺少的部分是:{ asJSON: true } 如果我补充说它工作正常。我正在使用 CDN 链接 - 出于遗留原因。目前尚不清楚asJSON 设置的作用。
    猜你喜欢
    • 2021-05-30
    • 2019-06-22
    • 2020-12-04
    • 2019-12-31
    • 2022-12-12
    • 2021-04-26
    • 2020-09-20
    • 2017-09-04
    • 2019-12-10
    相关资源
    最近更新 更多