Dev Play
Dev Play

Reputation: 85

The difference between axios and this.$axios

I am developing using nuxt and gridsome. These are all vue frameworks and I found that there are something interesting.

When I do like this:

<script>
    import axios from 'axios';
    ...
    created: function created() {
        axios.get(process.env.NUXT_ENV_API_URL + '/users').then(res=>{
        this.options=res.data.map(function(data){
            return {name: data.url, provider_id: data.provider_id};
        });
    }

I got 401 error(backend is laravel).

message: "Unauthenticated."

But when I use this, it's working.

<script>
import axios from 'axios';
...
created: function created() {
    this.$axios.get(process.env.NUXT_ENV_API_URL + '/users').then(res=>{
        this.options=res.data.map(function(data){
            return {name: data.url, provider_id: data.provider_id};
        });
}

Upvotes: 2

Views: 542

Answers (1)

Shizzen83
Shizzen83

Reputation: 3529

It's because Axios allows to create instances of itself which you can therefore customize. So when you do axios.get, underlying, Axios creates an instance on the fly before using it. When you do this.$axios.get, you use an already created instance which got customized somewhere else in your code (by adding some HTTP headers for example)

Upvotes: 2

Related Questions