1

我尝试使用 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]

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

之前谢谢。

4

2 回答 2

3

在幕后,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

于 2016-05-10T11:58:55.553 回答
1

如果您在节点环境中工作,则需要将 fetch 添加到global对象:

import fetch from 'node-fetch';

global.fetch = fetch;
于 2017-10-11T19:01:23.233 回答