Using Axios to Make API Requests With VueJS

Originally published at: https://serversideup.net/using-axios-to-make-api-requests-with-vuejs/

Let’s start with the basics, making API requests with Axios from within VueJS. This will give us a solid foundation to work from as we get into more complex requests. If this is your first time working with an API, it can seem intimidating. However, once you learn the basics, APIs begin to make a…

Hi! A very interesting series, just what I was looking for. But I have problem, in my API file, axios is not available. I’m using nuxtjs with @ nuxtjs / axios. I have tried everything I can think of but I have not been able to access axios in my services. Do you have any idea what the problem could be?
Thank you

Hi @quanpg ,

So Nuxt is interesting since it has a global built in Axios module (this is the next article I’ll write in the series :wink: ) and you don’t have to set it up like a raw VueJS SPA.

To answer your question, you have to structure your service a little bit different. In VueJS you’d follow this method: Build an API Wrapper with VueJS & Axios - Server Side Up.

With NuxtJS to do the same type of thing, you’d make a service where you inject the global $axios module into the service like this:

export default $axios => ({
    async index( params ){
        return await $axios.$get( '/songs', {
            params: params
        } );
    },

    show( id ){
        return await $axios.$get( '/songs/'+id );
    },

    update( id, data ){
        return await $axios.$put( '/songs/'+id, data );
    },

    create( data ){
        return await $axios.$post( '/songs/', data );
    },

    delete( id ){
        return await $axios.$delete( '/songs/'+id );
    }
})

Hope that helps!