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:
thisis 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 intopublic(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 tothis; use composables likeuseRuntimeConfig()instead.
Note on Sensitive API Keys
If your API_KEY needs to stay private:
- Keep it as
API_KEY=your-secret-keyin.env(noNUXT_PUBLIC_prefix) - Create a server route in
server/api/pgs.jsto 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 })
- Call this server route from your component:
<script setup> const response = await useFetch('/api/pgs') console.log(response.data.value) </script>
内容的提问来源于stack exchange,提问作者user20663233
相关产品推荐
相关产品推荐

