ApolloClient:永久违规1 –正确设置apollo客户端

时间:2019-08-11 22:20:46

标签: javascript graphql apollo apollo-client apollo-boost

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

首先,我想提一下,我使用nuxt's apollo module在nuxt内成功设置了一个阿波罗客户端。

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

现在,我想在一个JavaScript文件中设置一个阿波罗客户端,该文件要在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(程序包/.../ node_modules / ts-invariant / lib / invariant.js:16:28)

     

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

     

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

我用Google搜索了约1.5小时,但没有取得任何进展... 该错误消息非常含糊,我不知道该怎么办。

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

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

任何帮助,我们将不胜感激! 干杯 m

1 个答案:

答案 0 :(得分:2)

您的客户端配置缺少cache

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

这是您看到的actual error

  

为了初始化Apollo Client,必须在options对象中指定'link'和'cache'属性。   从Apollo Client 1.x迁移到Apollo Client 2.x时,这些选项是升级要求的一部分。   有关更多信息,请访问:https://www.apollographql.com/docs/tutorial/client.html#apollo-client-setup

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

相关问题