如何修复Next.js中的ApolloError: forward is not a function错误?
解决ApolloError: forward is not a function错误
问题原因
直接将onError创建的错误链路作为ApolloClient的link参数传入会触发该错误——错误链路本身无法独立完成请求转发逻辑,必须和HTTP链路配合才能处理完整的请求流程。
修正方案
导入HttpLink创建指向GraphQL API的HTTP链路,再将错误链路与HTTP链路组合后传入ApolloClient。以下是修正后的完整代码:
import { ApolloClient, InMemoryCache, HttpLink, ApolloLink } from '@apollo/client' import { onError } from '@apollo/client/link/error'; const API_URL = process.env.WORDPRESS_API_URL const errorLink = onError(({ graphQLErrors, networkError }) => { if (graphQLErrors) { graphQLErrors.forEach(({ message, locations, path }) => console.log(`[GraphQL error]: Message: ${message}, Location: ${JSON.stringify(locations)}, Path: ${JSON.stringify(path)}`) ); } if (networkError) { console.log(`[Network error]: ${JSON.stringify(networkError)}`); } }); // 创建HTTP链路 const httpLink = new HttpLink({ uri: API_URL }); // 组合错误链路与HTTP链路 const combinedLink = ApolloLink.from([errorLink, httpLink]); const client = new ApolloClient({ link: combinedLink, // 使用组合后的链路 cache: new InMemoryCache(), }) export default client
补充说明
ApolloLink.from()会按数组顺序执行链路:先经过错误链路处理错误逻辑,再将请求转发到HTTP链路发送给API。- 也可以用
errorLink.concat(httpLink)替代ApolloLink.from(),实现效果一致。
内容的提问来源于stack exchange,提问作者Tamara
相关产品推荐
相关产品推荐

