Axios is not defined in Vue

Viewed 16801

I'm trying to fetch data from Wordpress API. My console throws me an error "axios is not defined". Here is my post.vue component.

        <template>
        <div>
    <table class="table is-bordered">
                <thead>
                    <tr>
                        <th>Title</th>
                        <th>Posted at</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="post in posts" :key="post.id">
                        <td>{{post.title.rendered}}</td>
                        <td>{{post.date_gmt}}</td>
                    </tr>
                </tbody>
            </table>

            <pagination :pagination="pagination"
                        @prev="--postsData.page; getPosts();"
                        @next="postsData.page++; getPosts();">
            </pagination>
        </div>

    </template>


<script>
    import pagination from './pagination.vue'
    export default {
        mounted() {
            this.getPosts();
        },
        components: {
            'pagination': pagination
        },
        data() {
            return {
                postsUrl: 'http://localhost:8080/wp-json/wp/v2/posts',
                posts: [],
                postsData: {
                    per_page: 10,
                    page: 1
                },
                pagination: {
                    prevPage: '',
                    nextPage: '',
                    totalPages: '',
                    from: '',
                    to: '',
                    total: '',
                },
            }
        },
        methods: {

            getPosts() {
                axios
                .get(this.postsUrl, {params: this.postsData})
                    .then((response) => {
                        this.posts = response;
                        this.configPagination(response.headers);
                    })
                    .catch( (error) => {
                        console.log(error);
                    });
            },
            configPagination(headers) {
                this.pagination.total = +headers['x-wp-total'];
                this.pagination.totalPages = +headers['x-wp-totalpages'];
                this.pagination.from = this.pagination.total ? ((this.postsData.page - 1) * this.postsData.per_page) + 1 : ' ';
                this.pagination.to = (this.postsData.page * this.postsData.per_page) > this.pagination.total ? this.pagination.total : this.postsData.page * this.postsData.per_page;
                this.pagination.prevPage = this.postsData.page > 1 ? this.postsData.page : '';
                this.pagination.nextPage = this.postsData.page < this.pagination.totalPages ? this.postsData.page + 1 : '';
            }
        }
    }
</script>

I really have no idea what's wrong here, I installed axios, npm install axios,

Here is my main.js file

import Vue from 'vue'
import App from './App.vue'
import posts from "./components/posts.vue";
import axios from "axios";
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)

Vue.prototype.$axios = axios;

Vue.component('posts', posts);

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')

Can anybody help me with this? I don't see where i got wrong?

Thank you all

1 Answers

You need to add import axios from 'axios' to your component. Better yet create a config file called api.js file in your src directory and add something like this:

import axios from 'axios';

export default axios.create({
    baseURL: `http://127.0.0.1:8000/`,
    headers: {
        'Content-Type': 'application/json',
        'Authorization': "JWT " + localStorage.getItem('token')
    },
    xsrfCookieName: 'csrftoken',
    xsrfHeaderName: 'X-CSRFToken',
    withCredentials: true
});

Then in your components you import like this:

import API from '../api'

And do API.get instead of axios.get

This is benefical because:

  • You do not have to change your base url in 30 places when you need to change it.
  • You do not have to add the same headers over and over in your axios calls.
  • You can have shorter urls in your calls like this:

    API.get('foo/bar/') .then(response => { }

Related