You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用外部配置文件时Apollo Client访问错误httpEndpoint URL问题

问题原因及解决方案

核心原因

你的问题出在客户端环境变量未正确注入。

当使用外置clientConfigs文件时,process.env.API_URL在客户端代码中无法被正确解析(Nuxt2默认仅服务端能直接读取无前缀的环境变量),导致Apollo客户端的httpEndpoint变为undefined。此时Apollo会 fallback 到请求当前网站的根域名(比如你的Nuxt站点地址),而非WordPress的GraphQL端点,所以返回的是HTML页面,解析JSON时就会抛出Unexpected token '<'错误。

而使用内置clientConfigs时,@nuxtjs/apollo模块会自动处理配置中的环境变量,将其注入到客户端,因此能正常访问正确的端点。

解决方案

你可以通过以下两种方式修复:

方式1:使用NUXT_ENV_前缀的环境变量

将你的环境变量重命名为NUXT_ENV_API_URL(Nuxt2会自动将以NUXT_ENV_开头的变量注入到客户端),然后在外置配置文件中直接使用:

// apollo/client-configs/default.js
export default (context) => {
  return {
    httpEndpoint: process.env.NUXT_ENV_API_URL,
    cache: new InMemoryCache({ fragmentMatcher }),
  }
}

方式2:通过publicRuntimeConfig暴露变量

在nuxt.config.js中配置publicRuntimeConfig,将API地址暴露给客户端:

// nuxt.config.js
export default {
  // ...其他配置
  publicRuntimeConfig: {
    apiUrl: process.env.API_URL
  },
  apollo: {
    includeNodeModules: true,
    clientConfigs: {
      default: '@/apollo/client-configs/default.js',
    },
  },
}

然后在外置配置文件中通过context访问该变量:

// apollo/client-configs/default.js
export default (context) => {
  return {
    httpEndpoint: context.$config.apiUrl,
    cache: new InMemoryCache({ fragmentMatcher }),
  }
}

两种方式都能确保客户端代码能正确获取到GraphQL端点地址,解决跳转时的请求错误问题。

内容的提问来源于stack exchange,提问作者jminguely

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 18:55:18