8

With vue-resource, we could set the root url in main.js like so:

Vue.http.options.root = 'http://localhost:3000/api'

I tried replacing that with:

axios.defaults.baseURL = 'http://localhost:3000/api';
Vue.prototype.$http = axios

However, now my post calls don't work as expected, and Vue.http.post throws an error.

How is this achieved?

softcode
  • 4,358
  • 12
  • 41
  • 68

2 Answers2

6

With axios, one can create another instance having a custom config

var my_axios = axios.create({
  baseURL: 'http://localhost:3000/api',
});

From here one can use my_axios for operations. You could prototype the custom axios instance into Vue:

Vue.prototype.$http = my_axios
Nicolas Heimann
  • 2,561
  • 16
  • 27
1
import axios from 'axios';

export const HTTP = axios.create({
  baseURL: `http://localhost:3000/api/`,
  headers: {
    Authorization: 'Bearer {token}'
  }
})

You could now use HTTP like so

<script>
import {HTTP} from './http-common';

export default {
  data: () => ({
    posts: [],
    errors: []
  }),

  created() {
    HTTP.get(`posts`)
    .then(response => {
      this.posts = response.data
    })
    .catch(e => {
      this.errors.push(e)
    })
  }
}
</script>
Emad Adly
  • 1,435
  • 12
  • 6
  • 1
    If you’d like to access this.$http like in vue-resource, you can just set Vue.prototype.$http = axios. – Emad Adly Apr 30 '17 at 05:10