Vue throws an error stating that Axios has not been defined

I'm having trouble fetching data from the Wordpress API. When I try to do so, my console shows an error message saying "axios is not defined". Below is the code for 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 am baffled as to what might be causing this issue. I made sure to install axios using npm install axios.

Below is the content of 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')

If anyone has any insights on how to resolve this issue, your help would be greatly appreciated!

Thank you all for your assistance.

Answer №1

To improve your component, make sure to include the line import axios from 'axios'. Alternatively, consider creating a configuration file named api.js within your src directory, and incorporate the following code:

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
});

Subsequently, in your components, import as shown below:

import API from '../api'

Utilize API.get instead of axios.get.

Adhering to this approach is advantageous due to the following reasons:

  • No need to update the base URL in numerous locations when modifications are required.
  • Avoid repetitive inclusion of identical headers in axios requests.
  • Easier utilization of shorter URLs in calls such as:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The file name is not compatible with 'eslint' functionality

I attempted to use the solution provided in this Stack Overflow thread for the error message 'eslint' is not recognized as an internal or external command. I successfully created a .eslintrc.json file with the following content: { "extends" ...

The perplexing simplicity of closure

Currently, I am endeavoring to enhance my knowledge of JavaScript closures. Let's consider the following two scenarios in Node.js: function A(){ console.log(data); //this will result in a null pointer } module.exports = function(data){ re ...

The jQuery equalTo function is throwing an error because it doesn't recognize that the two emails are identical

Why is it that even though both email addresses are exactly the same, I still get an error message saying they don't match? The error seems to be with email2 specifically. * Email: <input type='text' name='email' /> <br/ ...

Tips on finding the most budget-friendly item in a Vue array

I'm working with an array called item.warehouse_positions that contains various prices and IDs. I want to display only one item.id with the lowest price. How can I achieve this? <div v-for='(item, index) in item.warehouse_positions' :key= ...

Why is the child's CSS hover not functioning when the body has an event listener attached to it?

Check out the repository link here: https://codepen.io/Jaycethanks/pen/WNJqdWB I am trying to achieve a parallax effect on the body and image container, as well as a scale-up effect on images when hovered over. However, the hover functionality is not work ...

Running npm build/deploy is not functioning properly and is throwing a "failed to compile errors" message

I attempted to use npm run deploy/build, but it was unsuccessful and resulted in an error in the terminal. As a novice in git and github, I am looking to upload the changes I made in my most recent commit to my github pages. However, no matter how many tim ...

Express.js Routes with Prefix

Is it possible to add a prefix to only certain routes in express.js? I understand that using app.router() allows for adding a mount point, but this applies to all routes. I'm interested in finding a method to insert /api/v1/ before several routes wit ...

JavaScript: Eliminate a specific element and retrieve the modified array

Is there a way to remove only one instance of an item from an array, even if there are multiple duplicates of that item? For example: let array = ["abc", "def", "ghi", "def"]; const toRemove = "def"; I attempted to find the index and splice the array, but ...

AngularJS and Rails: Error detected - provider 'e' is unknown

Upon transitioning to the production server utilizing Rails 4 and AngularJS, I encountered an error: [$injector:modulerr] Failed to instantiate module EcoApp due to: Error: [$injector:unpr] Unknown provider: e. After exploring various Stack Overflow thre ...

JavaScript does not function properly when interacting with the result of a POST request made through $.ajax

Question: After including jQuery files and functions in index.php, do I also need to include them in select.php? To clarify my issue, here is the problem I am facing: Initially, I am trying to send data to select.php using jQuery's $.ajax. The data ...

Leverage the power of express-session in your NextJS project

Currently, I am working on developing a login system using NextJS and MySQL. I am looking to implement sessions for user login, but I am unsure of how to integrate express-session with NextJS. Can anyone provide guidance on whether express-session can be ...

I need help with a MutationObserver script, kindly provide your assistance

Can someone help me with writing this code? I'm not very familiar with javascript. Here is the code I have: <ul id="theul"> <li id="firstli" style="display: something;"></li> <li id="secondli" style="display: something;"&g ...

Setting a proper prop path for nested data within a table component in Element UI using Vue JS

I'm currently facing an issue with form validation in a table layout using element-ui. Specifically, I am struggling to pass a valid prop to the el-form-item component. The structure of my data model is as follows: form: { invoices: [ { ...

Resize the main container to fit the floated elements

I've been working on constructing a family tree, and the last part of the functionality is proving to be quite challenging for me. My family tree consists of list elements that are all floated to the left. Currently, when the tree expands beyond the ...

Obtain the Xpath for the element with a certain tag located closest to the given element in its immediate surrounding

Within my HTML document, I have a specific element with an id of uniqueId. There are multiple nested tags surrounding this element, and I am trying to retrieve a particular tag that is closest to it. For example: <div> <div> ...

file_put_contents - store user-defined variables

When I execute this script, it successfully generates the html page as expected. However, I am encountering challenges in incorporating variables, such as the $_GET request. The content is enclosed in speech marks and sent to a new webpage on my site usin ...

What is the best way to identify specific strings within a given syntax and then separate them into an array without considering their original order

My task is to divide a string into separate parts. This is how I want it: I begin with an original string let allString = 'This is the test to replace the string'; I will convert the original string into an array based on another array. let to ...

Creating a pop-up effect for a div in the center of a table cell using HTML and CSS

I am currently working with Angular and facing a challenge where I need to display a div like a popup in a table cell when clicked. Despite having the click event logic in place, I am unsure of how to achieve this without using external libraries such as B ...

Inquiring about the intricacies of using Regular Expressions in

Can anyone provide a regex that only allows the characters 0-9, a-z, A-Z, hyphen, question mark, and "/" slash, with a character length between 5 to 15? I attempted the following approach, but it did not yield the desired result: var reg3 = /^([a-zA-Z0-9? ...

Using JavaScript's indexOf method with multiple search values

I have a data set that includes various duplicate values ["test234", "test9495", "test234", "test93992", "test234"] I am looking to find the positions of every instance of test234 in the dataset Although ...