Askar
Askar

Reputation: 5854

How to use env var for API in NuxtJS axios?

I have a working snippet

const response = await axios.get('http://example.com/categories')

But I want to refactor it by moving http://example.com to .env.

I made the following changes but successful

  1. .env contains http://example.com
  2. const response = await axios.get('/categories')
  3. In nuxt.config.js:
       publicRuntimeConfig: {
        axios: {
          baseURL: process.env.API_URL,
        },
      },

Result: It's trying to access http://localhost:3000/categories

UPDATE:

Thanks to @AmirhosseinShahbazi for his answer.

Besides his advice on fix, I have also changed nuxt.config.js

from

       publicRuntimeConfig: {
        axios: {
          baseURL: process.env.API_URL,
        },
      },

to

  axios: {
    baseURL: process.env.API_URL,
  },

Upvotes: 0

Views: 755

Answers (1)

Amirhossein Shahbazi
Amirhossein Shahbazi

Reputation: 1111

You're using Nuxt's Axios module in the project. There's no need to import Axios for using it. By importing it, you're using a new instance, not the one you've actually injected with baseURL.

Just replace await axios.get with await this.$axios.get and remove your import.

<script>
export default {
  name: 'App',
  data() {
    return {
      categories: [],
      error: null,
    }
  },
  async mounted() {
    try {
      const response = await this.$axios.get('categories')
      this.categories = response.data
    } catch (error) {
      this.error = error
    }
  },
}
</script>

Upvotes: 3

Related Questions