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

Nuxt 3中publicRuntimeConfig始终为undefined问题求助

Nuxt3 publicRuntimeConfig 配置失效解决办法
  • 修正 nuxt.config.js 中的环境变量写法
    你当前代码里的'${BASE_API_URL}'是字符串字面量,不会自动解析环境变量,需改为通过process.env读取。同时可添加默认值避免空值:

    // nuxt.config.js
    export default defineNuxtConfig({
      publicRuntimeConfig: {
        BASE_API_URL: process.env.BASE_API_URL || 'http://localhost/api',
        BASE_API_BROWSER_URL: process.env.BASE_API_BROWSER_URL || process.env.BASE_API_URL || 'http://localhost/api'
      }
    })
    

    若使用.env文件,Nuxt3约定公共环境变量需以NUXT_PUBLIC_开头,例如.env内容:

    NUXT_PUBLIC_BASE_API_URL=http://localhost/api
    NUXT_PUBLIC_BASE_API_BROWSER_URL=http://localhost/api
    

    此时无需手动配置publicRuntimeConfig,Nuxt会自动注入这些变量到config.public中。

  • 页面中正确获取配置
    在<script setup>中必须调用useRuntimeConfig()获取配置对象,且公共配置在public属性下:

    <script setup>
    const config = useRuntimeConfig()
    const { data: name } = await useAsyncData('name', () => 
      $fetch(`${config.public.BASE_API_BROWSER_URL}/message`)
    )
    </script>
    
  • 验证配置生效状态
    打印配置时需查看public子对象:

    console.log(config.public) // 应包含BASE_API_URL、BASE_API_BROWSER_URL配置项
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 19:25:26