3

我是 GraphQL 和 Apollo 的新手,我真的很难在 node.js 中设置 apolloClient。

首先我想提一下,我使用nuxt 的 apollo 模块成功地在 nuxt 中设置了一个 apollo 客户端。

所以我完全确定我的端点和我的令牌正在工作。

现在我想在一个 JavaScript 文件中设置一个 apollo 客户端,我想在 node.js 中运行它。

import fetch from 'node-fetch'
import gql from 'graphql-tag'
import { ApolloClient } from 'apollo-client'
import { createHttpLink } from 'apollo-link-http'
import { setContext } from 'apollo-link-context'

export default function generateRoutesFromData(
  options = {
    api: [],
    query: '',
    token: '',
    bundle: '',
    homeSlug: 'home',
    errorPrefix: 'error-'
  }
) {
  const uri = 'https://example.com/api'
  const token =
    '...fPsvYqkheQXXmlWgb...'

  const httpLink = createHttpLink({ uri, fetch })

  const authLink = setContext((_, { headers }) => {
    // return the headers to the context so httpLink can read them
    return {
      headers: {
        ...headers,
        authorization: `Bearer ${token}`
      }
    }
  })

  const GET_PAGES = gql`
    {
      helloWorld
    }
  `

  const client = new ApolloClient({
    link: authLink.concat(httpLink),
    fetch
  })

  client
    .query({
      query: GET_PAGES
    })
    .then(result => {
      console.log('result: ', result)
    })
    .catch(error => {
      console.log('error: ', error)
    })

  // for now just return array with a test string
  // later on: return all uris fetched via graphql
  return ['/test']
}

如果我在节点中运行它,我会收到以下错误:

致命的不变违规:1(参见https://github.com/apollographql/invariant-packages)00:05:36

不变违规:不变违规:1(请参阅https://github.com/apollographql/invariant-packages

在新的 InvariantError (packages/.../node_modules/ts-invariant/lib/invariant.js:16:28)

在新的 ApolloClient (packages/.../node_modules/apollo-client/bundle.umd.js:2483:55)

在对象的 generateRoutesFromData (packages/.../src/routes/generateRoutesFromData.js:41:18)。(nuxt.config.js:158:10) 在 Generator.next ()

我用谷歌搜索了大约 1.5 小时并没有取得任何进展......错误消息非常神秘,我不知道我能做什么。

我必须说围绕 apollo 的整个文档非常混乱。Apollo-boost 并封装了 apollo 客户端所有其他的东西。不同的认证方式等。

我找到了这个页面: https ://www.apollographql.com/docs/react/advanced/boost-migration/ 但它似乎很复杂,我不确定这是否会对我有任何帮助......

对此的任何帮助都非常感谢!干杯米

4

1 回答 1

7

您的客户端配置缺少cache

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache(), // <-- ADD ME
})

这是您看到的实际错误:

为了初始化 Apollo 客户端,您必须在选项对象中指定“链接”和“缓存”属性。这些选项是从 Apollo Client 1.x 迁移到 Apollo Client 2.x 时升级要求的一部分。欲了解更多信息,请访问:https ://www.apollographql.com/docs/tutorial/client.html#apollo-client-setup

不变的错误在生产中被故意混淆。我不确定为什么你会在本地看到这种行为,但也许 Nuxt在代码评估之前的某个时间点设置NODE_ENV为。production

于 2019-08-12T15:52:22.460 回答