我正在尝试使用node.js服务器上的一个Apollo客户端通过以下代码与另一个GraphQL应用程序接口:
import fetch from 'node-fetch'
import { createHttpLink } from 'apollo-link-http'
import ApolloClient from 'apollo-boost'
import { API_URL } from '...'
const client = new ApolloClient({
link: createHttpLink({
uri: API_URL,
fetch: fetch,
}),
})
这会产生以下错误:
module initialization error: Error
fetch is not found globally and no fetcher passed, to fix pass a fetch for
your environment like https://www.npmjs.com/package/node-fetch.
For example:
import fetch from 'node-fetch';
import { createHttpLink } from 'apollo-link-http';
const link = createHttpLink({ uri: '/graphql', fetch: fetch });
at Object.checkFetcher (/var/task/node_modules/apollo-link-http-common/lib/bundle.umd.js:78:19)
at createHttpLink (/var/task/node_modules/apollo-link-http/lib/bundle.umd.js:32:30)
at new HttpLink (/var/task/node_modules/apollo-link-http/lib/bundle.umd.js:203:38)
at new DefaultClient (/var/task/node_modules/apollo-boost/lib/index.js:80:24)
我知道,默认情况下,Apollo客户端期望在浏览器上下文中运行,其中fetch
方法将可用,并且在node.js中,我需要polyfill或以其他方式提供fetch
方法,但我很难弄清楚如何做到这一点。
按照https://www.apollographql.com/docs/link/#apollo-client上的示例代码,我似乎应该能够使用link
选项传递此信息,并且阅读apollo-boost
源代码似乎表明您可以使用fetcherOptions
传递此信息,但这两种解决方案似乎都不起作用。
有没有人可以提供一些示例代码,用于在node.js中使用fetcher初始化Apollo客户端?
下面是我的package.json
以供参考
{
"name": "API-Service",
"version": "1.0.0",
"description": "",
"private": true,
"scripts": {},
"dependencies": {
"apollo-boost": "^0.1.6",
"apollo-link-http": "^1.5.4",
"graphql": "^0.13.2",
"babel-polyfill": "^6.26.0",
"json-rules-engine": "^2.1.0",
"node-fetch": "^2.1.2",
"mysql": "^2.15.0"
}
}
发布于 2018-06-05 06:31:55
事实证明,apollo-boost
库提供的ApolloClient
不接受link
选项。切换到使用普通apollo-client
允许您指定获取机制。
尽管apollo-boost
和apollo-client
都在文档中导出了ApolloClient
,但它们采用了截然不同的选项。
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(),
})
发布于 2018-06-06 19:31:22
如果您仍然想在Node.js中使用Apollo Boost,但需要多填充浏览器的本机fetch API,请尝试cross-fetch。我在here上的最小示例中使用了它。这就是如何在安装后使用它:
import 'cross-fetch/polyfill';
import ApolloClient from 'apollo-boost';
const client = new ApolloClient({
uri: 'https://api.domain.com/graphql',
});
发布于 2019-08-09 16:53:07
您可以从apollo-boost
将fetch
选项直接添加到ApolloClient
中。以下是示例代码
参考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
});
使用apollo-boost
版本0.4.3
进行了测试
https://stackoverflow.com/questions/50688998
复制相似问题