javascript - Creating an instance of axios in Vue not working - Stack Overflow

I am using axios for AJAX in Vue. In the article written by You, he mentioned that we can set Vue.proto

I am using axios for AJAX in Vue. In the article written by You, he mentioned that we can set Vue.prototype.$http = axios and I can use this.$http in Vue instance. It works fine.

However, if I want to create an axios instance to $http, like

Vue.prototype.$http = axios.create({
  baseURL: '/'
})

It does not work when I use this.$http.get('/relativeURL'). It seems that it cannot access the config I set. That is, it will not send request to

In another way, if I set axios instance in any other object, such as Vue.prototype.$axios = axios.create({config}). It works successfully.

Could someone explain why this happen ??

I am using axios for AJAX in Vue. In the article written by You, he mentioned that we can set Vue.prototype.$http = axios and I can use this.$http in Vue instance. It works fine.

However, if I want to create an axios instance to $http, like

Vue.prototype.$http = axios.create({
  baseURL: 'https://app.herokuapp./'
})

It does not work when I use this.$http.get('/relativeURL'). It seems that it cannot access the config I set. That is, it will not send request to https://app.herokuapp./relativeURL

In another way, if I set axios instance in any other object, such as Vue.prototype.$axios = axios.create({config}). It works successfully.

Could someone explain why this happen ??

Share Improve this question edited Apr 14, 2017 at 11:01 PJCHENder asked Apr 14, 2017 at 8:37 PJCHENderPJCHENder 6,0203 gold badges21 silver badges38 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

While defining it at Vue instance level might have its own merit, I don't like to pollute the global namespace. What my approach is, I have a gateway folder, where I have different files for axios instance, such as:

backend-api.js

import axios from 'axios'
export default axios.create({
  baseURL: 'http://YourAPiIp:9090/api/v1',
  timeout: 100000,
  headers: {
    'Content-Type': 'application/json'
  }
})

Now you can import it the place you want and use it:

import backendApi from '../../gateways/backend-api'

You set

Vue.prototype.$https = axios.create({
  baseURL: 'https://app.herokuapp./'
})

And use

this.$http...

Typo in property name (https vs http).

Leave it as $http. Or simply don't even declare $http if it misleads you - use just this.axios.get...

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743906160a4527530.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信