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

Nuxt 3中.env文件使用方法及API配置报错解决指南

Fixing Nuxt 3 Environment Variables & Axios Issues

Step 1: Remove Unnecessary Dependency

Nuxt 3 has built-in support for environment variables, so you don't need @nuxtjs/dotenv. Uninstall it with:

npm uninstall @nuxtjs/dotenv

Step 2: Correctly Configure Environment Variables

In Nuxt 3, client-accessible environment variables must be prefixed with NUXT_PUBLIC_. Update your root .env file:

NUXT_PUBLIC_API_URL=https://your-api-base-url.com
NUXT_PUBLIC_API_KEY=your-api-authorization-key

Note: If your API_KEY is sensitive and shouldn't be exposed to the browser, skip the NUXT_PUBLIC_ prefix and handle the request on the server side (see note at the end).

Step 3: Fix Axios Code

Your code has two critical issues:

  • this is undefined in <script setup>
  • You’re mixing direct axios imports with this.$axios (which isn’t set up)

Here’s the corrected component code:

<template>
</template>

<script setup>
import axios from 'axios'

// Access Nuxt's runtime config to get env vars
const config = useRuntimeConfig()

// Set axios global defaults
axios.defaults.baseURL = config.public.API_URL
axios.defaults.headers.common['Authorization'] = config.public.API_KEY

// Make the API request (clean await syntax)
try {
  const response = await axios.get('/pgs')
  console.log(response.data)
} catch (error) {
  console.error('Failed to fetch data:', error)
}
</script>

Step 4: Restart Dev Server

Nuxt 3 caches environment variables on startup. Stop your dev server and restart it to load the updated .env values.

Key Concepts to Learn

  • Runtime Config: Nuxt 3’s useRuntimeConfig() lets you access environment variables, split into public (client-side) and private (server-only) sections.
  • Client vs Server Variables: Variables prefixed with NUXT_PUBLIC_ are sent to the browser. Never put sensitive data (like secret API keys) in public variables—handle those requests on the server.
  • <script setup>: This syntax doesn’t have access to this; use composables like useRuntimeConfig() instead.

Note on Sensitive API Keys

If your API_KEY needs to stay private:

  1. Keep it as API_KEY=your-secret-key in .env (no NUXT_PUBLIC_ prefix)
  2. Create a server route in server/api/pgs.js to proxy the request:
export default defineEventHandler(async (event) => {
  const config = useRuntimeConfig()
  const response = await $fetch('/pgs', {
    baseURL: config.API_URL,
    headers: { Authorization: config.API_KEY }
  })
  return response
})
  1. Call this server route from your component:
<script setup>
const response = await useFetch('/api/pgs')
console.log(response.data.value)
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 08:25:23