0

I'm using the asyncData with axios to get a local.json file from my static folder. I just want to get it locally for the moment as i've added all my methods as i'm waiting for my API to be built.

To use async I need the full path and URL so I need an env variable, however I keep getting a 403 on my server or I get a random error. I need the path to be whatever the URL is hosted on in my axios call.

The URL needs to be dynamic because I'm using gitlab CI and the URL changes depending what branch i'm on, so I can't set a Dev, Prod URL

If I replace context.env.baseUrl with my localIP it works but I need the URL to be "my hosted URL". I need this to be a variable as i'm using gitlab with different URL's

Async Data

asyncData(context) {
        return axios.get(context.env.baseUrl+'/products.json')
        .then(response => {
        return {
           servers: response.data.products
        }
    })
    .catch(e => context.error(e))
 }

nuxt.config.js

env: {
  // The baseUrl needs to be dynamic - whatever the server is on
  baseUrl: process.env.BASE_URL || 'http://localhost:3000'
}
ottz0
  • 2,595
  • 7
  • 25
  • 45

3 Answers3

1

If you want to use static file present in same project then just import/require it instead of using axios. See example below

<script>
export default {
  asyncData() {
    const servers = require('@/static/local.json')

    return {
      servers
    }
  }
}
</script>
ImZedi
  • 294
  • 4
  • 15
  • 1
    I want to async it though so It renders on the server for SEO, then I lose access to this if I use a sync data? – ottz0 May 25 '20 at 10:58
-1

You can create an axois instance and set a base URL to avoid the headache.

const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
});

See: https://github.com/axios/axios#axioscreateconfig

drdgvhbh
  • 510
  • 4
  • 4
-1

One of many ways that I know and the easiest is using axios module for nuxt. Many of the axios config pain points are addressed via this module instead of using standalone axios package. Then in your nuxt.config.js

Add this like so

axios: {
  baseURL: () => {
    if (process.env.NODE_ENV !== "production") {
      return 'localhost:5000/api/';    
    }
    return https://www.example.com/api/;
  }
}

USAGE IN NUXT PAGES

async asyncData({ $axios }) {
    try {
      let response = await $axios.get("/your-api-route");
      return response;
    } catch (err) {
      console.log(err);
    }
  }
Leo
  • 77
  • 1
  • 10