使用Apollo持久化查询链接时遇TypeError:URL实例触发参数类型错误求助
问题
按照graphql-ruby-persisted_queries的文档配置Apollo持久化查询链接时,遇到了一个矛盾的类型错误:
TypeError [ERR_INVALID_ARG_TYPE]: The "filename" argument must be of type string or an instance of URL. Received an instance of URL
明明错误提示允许传入URL实例,实际传入后却触发报错,我的配置代码如下:
const httpLink = new HttpLink({ uri: apiUri, fetchOptions: { agent: new Agent({ keepAlive: true }), next: { revalidate: 300, }, }, }) const timeoutLink = new ApolloLinkTimeout(15_000) const errorLink = onError(({ graphQLErrors, networkError, operation }) => { if (graphQLErrors) graphQLErrors.forEach(({ message, locations, path }) => log.error( `[GraphQL error]: Message: ${message}, Location: ${JSON.stringify( locations )}, Path: ${path}, operation: ${operation.operationName}` ) ) if (networkError) { if (networkError.message.includes("Timeout exceeded")) { log.error(`Timeout exceeded Operation Name: ${operation.operationName}`) } else { log.error( `[Network error]: ${networkError}, operation: ${operation.operationName}` ) } } }) const persistedQueriesLink = createPersistedQueryLink({ sha256 }) const links = process.env.VERCEL_ENV ? [errorLink, timeoutLink, persistedQueriesLink, httpLink] : [errorLink, persistedQueriesLink, httpLink] export const apolloLink = ApolloLink.from(links)
解决方案
这个错误大概率是不同环境/模块的URL实例不兼容导致的——比如你代码里用的是Node.js内置url.URL生成的实例,但某个依赖库的类型校验逻辑只认浏览器环境的URL,或者库本身存在类型判断bug。
直接有效的修复方法:
- 把
apiUri从URL实例转换成字符串传入HttpLink:const httpLink = new HttpLink({ uri: apiUri.toString(), // 将URL实例转为字符串格式 fetchOptions: { agent: new Agent({ keepAlive: true }), next: { revalidate: 300, }, }, }) - 同时检查
createPersistedQueryLink的sha256参数:确保传入的是标准sha256实现(比如Node.jscrypto模块的createHash('sha256')相关方法),避免自定义函数导致的潜在兼容问题。
如果转字符串后还是报错,建议升级@apollo/client和apollo-link-persisted-queries到最新版本,这类类型校验的bug通常会在后续版本中被修复。
内容的提问来源于stack exchange,提问作者Luiz Henrique Guerra
相关产品推荐
相关产品推荐

