Am using Nuxt-3 as my framework for the project and am very new to the framework too and when I was integrating api for my project and I was getting the response later when I tried to use api as global variable from the .env file in the root; but am unable to get the response as am getting error on the console hence forth kindly guide me on the right path in a simple way of explanation so I can sort the issue as well learn new concepts. I installed the dependencies with: npm install --save-dev @nuxtjs/dotenv
The code I tried was:
<template>
</template>
<script setup>
import axios from 'axios'
axios.defaults.baseURL = process.env.API_URL
axios.defaults.headers.common['Authorization'] = process.env.API_KEY
const response = await this.$axios.get('/pgs').then(response => response.data)
console.log(response)
</script>
You don't need any dependency when you use .env file for your project. In all my projects, this is process I do when I store important data.
[email protected]nuxt.config.tsfile, add thisruntimeConfig: { EMAIL: process.env.EMAIL, },useRuntimeConfigcomposables See more details https://nuxt.com/docs/api/composables/use-runtime-config#useruntimeconfig.See example on stackblitz https://stackblitz.com/edit/nuxt-starter-g534de?file=nuxt.config.ts