"TypeError: Cannot read property 'get' of undefined", Axios, Vue.JS
Asked Answered
O

2

5

I am getting this strange error from Vue when trying to access get request from api using axios, I am getting "TypeError: Cannot read property 'get' of undefined"

enter image description here

 <template>
    <div class="home">
        <h1>{{ msg }}</h1>
        <p>Welcome to your new single-page application, built with <a href="https://vuejs.org" target="_blank">Vue.js</a>.</p>
    </div>
</template>

<script>
    var Vue = require('vue');

   // import axios from "axios";

    window.axios=require('axios');
    export default {
        name: 'Home',
        props: {
            msg: String
        },
        component: {
        },   
        mounted: function () {
            alert('Hi ');
            this.axios.get('https://api.github.com/users')
                .then(value => {
                    alert(value);
                         
                });
        }

    };
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>


 
Overspread answered 29/8, 2020 at 21:16 Comment(3)
It should be just axios.get, not this.axios.get. You may see this.axios used in some examples but in those cases they have stored axios on this, which doesn't appear to be the case in your code.Scarification
I also suggest sticking to the import approach rather than using require and window.Scarification
Thank you @skirtle, much appreciate sir :)Overspread
R
7

this does not reference to window in your case. A better approach would be importing axios in the component:

import axios from 'axios';

A more efficient way is to set it once globally in the main.js file:

Vue.prototype.$http = axios

And using it where ever you want as this.$http

Romanticism answered 29/8, 2020 at 21:21 Comment(0)
A
0

I had same issue and solved it by adding type="module".

Anatomize answered 23/11, 2023 at 12:50 Comment(2)
Can you clarify where/how exactly you added type="module"?Barbell
where is added the config?Eroticism

© 2022 - 2024 — McMap. All rights reserved.