【问题标题】:Unable to query from non-Apollo GraphQL server from Apollo client无法从 Apollo 客户端查询非 Apollo GraphQL 服务器
【发布时间】:2016-08-31 03:50:25
【问题描述】:

我尝试使用 Apollo Client 向非 Apollo GraphQL 服务器发出请求,如下所示:

import ApolloClient, { createNetworkInterface } from 'apollo-client';

// Register gql globally
import { registerGqlTag } from 'apollo-client/gql';
registerGqlTag();

const networkInterface = createNetworkInterface(' http://localhost:8080/graphql', {
  headers: {
  'Content-type': "application/json"
  }
});

var client = new ApolloClient({
  networkInterface
});

client.query({
  query: gql`
    query getTodo($todoId: Int!) {
      node(id: $todoId) {
        ... on Todo {
          id
          text
        }
      }
    }
  `,
  variables: {
    todoId: "todo:100000",
  },
  forceFetch: false,
}).then((graphQLResult) => {
  var errors  = graphQLResult.errors;
  var data = graphQLResult.data;

  if (data) {
    console.log('got data', data);
  }

  if (errors) {
    console.log('got some GraphQL execution errors', errors);
  }
}).catch((error) => {
  console.log('there was an error sending the query', error);
});

但是,我在运行代码时不断收到错误消息: there was an error sending the query [ReferenceError: fetch is not defined]

我尝试搜索与此相关的问题,但是文档并没有真正的帮助。

之前谢谢。

【问题讨论】:

标签: graphql apollo


【解决方案1】:

在幕后,Apollo 客户端使用fetch,这是一个围绕发出 http 请求的新标准。它存在于大多数主要浏览器中,但在 node 或 IE / Edge 中找不到。团队之所以选择使用 fetch,是因为它的采用率正在增长,而且适用于旧版浏览器和节点的 polyfills 的可用性。

我们在此问题的文档中添加了一个部分:http://docs.apollostack.com/apollo-client/core.html#fetch-polyfill

要深入了解使用 fetch 的决定,请查看此问题:https://github.com/apollostack/apollo-client/pull/126

【讨论】:

【解决方案2】:

如果您在 node 环境中工作,则需要将 fetch 添加到 globalobject:

import fetch from 'node-fetch';

global.fetch = fetch;

【讨论】:

    猜你喜欢
    • 2018-03-25
    • 2018-09-18
    • 2020-10-25
    • 2023-04-02
    • 2019-10-22
    • 2020-06-12
    • 1970-01-01
    • 2019-06-22
    • 2019-09-17
    相关资源
    最近更新 更多