问题描述
我将 apollo 添加到我的 nuxt 项目中。我构建了一个登录,它在登录成功时设置 jwt,但是当它过期时,我收到一个 nuxt 错误。我尝试使用 apollo 错误处理程序捕获 nuxt 错误,但该处理程序不起作用。 我如何才能捕获错误以设置新令牌?
nuxt.config.js
....
apollo: {
authenticationType: 'Bearer',clientConfigs: {
default: '~/graphql/config/config.ts'
},errorHandler: '~/plugins/apollo-error-handler.ts',tokenName: 'apollo-token'
}
...
我的错误处理程序看起来像:
import { Context } from '@nuxt/types'
export default ({ redirect,app,$apolloHelpers,...rest }: Context) => {
console.log(1,rest)
}
解决方法
我在我的 nuxt.config.js
> apollo.clientConfigs.default: '@/plugins/nuxt-apollo-config.js'
(不是 errorHandler
所以)中设置了以下内容,它有点适用于我的用例。
不是专家,关于 the documentation 可能有 10 种不同的处理方式。
我按照 Apollo Link overview 设置了以下内容。
import { onError } from '@apollo/client/link/error'
import { setContext } from 'apollo-link-context'
import { from } from 'apollo-link'
import { InMemoryCache,IntrospectionFragmentMatcher } from 'apollo-cache-inmemory'
import { createHttpLink } from '@apollo/client/core'
import schema from '../apollo/schema.json'
const fragmentMatcher = new IntrospectionFragmentMatcher({
introspectionQueryResultData: schema,})
export default ({ app,$config: { baseUrlGraphql } }) => {
const headersConfig = setContext(() => ({
credentials: 'same-origin',headers: {
// ...
},}))
const link = onError(({ graphQLErrors,networkError,operation,response }) => {
if (graphQLErrors) {
graphQLErrors.map(() => console.log('error my dude'))
}
if (networkError) {
console.log('and another one!')
}
})
const cache = new InMemoryCache({ fragmentMatcher,resultCaching: false })
return {
defaultHttpLink: false,link: from([
headersConfig,link,createHttpLink({
credentials: 'include',uri: baseUrlGraphql,fetch: (uri,options) => {
return fetch(uri,options)
},}),]),cache,}
}
不确定它是否有帮助,但这就是我所拥有的。