ApolloClient: Invariant Violation 1 – 正确设置 apollo 客户端

ApolloClient: Invariant Violation 1 – setup apollo client properly

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

首先我想提一下,我使用 nuxt's apollo module.

在 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']
}

如果我 运行 在节点中执行此操作,我会收到以下错误:

FATAL Invariant Violation: 1 (see https://github.com/apollographql/invariant-packages) 00:05:36

Invariant Violation: Invariant Violation: 1 (see https://github.com/apollographql/invariant-packages)

at new InvariantError (packages/.../node_modules/ts-invariant/lib/invariant.js:16:28)

at new ApolloClient (packages/.../node_modules/apollo-client/bundle.umd.js:2483:55)

at generateRoutesFromData (packages/.../src/routes/generateRoutesFromData.js:41:18) at Object. (nuxt.config.js:158:10) at Generator.next ()

我用谷歌搜索了大约 1.5 小时,但没有取得任何进展... 错误信息非常隐晦,我不知道该怎么办。

我必须说关于 apollo 的整个文档非常混乱。 Apollo-boost 并且包装了 apollo 客户端所有其他的东西。不同的身份验证方式等

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

非常感谢任何帮助! 干杯 米

您的客户端配置缺少 cache:

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

这是您看到的actual error

In order to initialize Apollo Client, you must specify 'link' and 'cache' properties in the options object. These options are part of the upgrade requirements when migrating from Apollo Client 1.x to Apollo Client 2.x. For more information, please visit: https://www.apollographql.com/docs/tutorial/client.html#apollo-client-setup

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