Using ApolloClient with node.js. “fetch is not found globally and no fetcher passed”

…衆ロ難τιáo~ 提交于 2019-12-01 02:53:30

It turns out that the ApolloClient provided by the apollo-boost library does not accept a link option. Switching to use the vanilla apollo-client allows you to specify your fetching mechanism.

Although apollo-boost and apollo-client both export an ApolloClient in the docs, they take wildly different options.

import fetch from 'node-fetch'
import { createHttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'

import ApolloClient from 'apollo-client'
import { API_URL } from '...'

const client = new ApolloClient({
  link: createHttpLink({
    uri: API_URL,
    fetch: fetch,
  }),
  cache: new InMemoryCache(),
})

If you still want to use Apollo Boost in Node.js but need to polyfill the native fetch API of the browser, try out cross-fetch. I used it for my minimal example over here. And that's how it can be used after installing it:

import 'cross-fetch/polyfill';
import ApolloClient from 'apollo-boost';

const client = new ApolloClient({
  uri: 'https://api.domain.com/graphql',
});

You can add fetch option directly to the ApolloClient from apollo-boost. Here is the example code

Ref. https://www.apollographql.com/docs/react/essentials/get-started/#configuration-options

import ApolloClient from 'apollo-boost';
import fetch from 'node-fetch';

const client = new ApolloClient({
    fetch: fetch
});

Tested with apollo-boost version 0.4.3

You can use the whatwg-fetch polyfill:

yarn add whatwg-fetch

The installation instructions depend on your usage (e.g Babel, Webpack etc.) and are in the provided link.

In my case I needed the polyfill for my Jest tests so I just put this in my test setup file:

import 'whatwg-fetch';
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!