Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switching from vue-resource to axios

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?

like image 718
softcode Avatar asked Jan 26 '17 17:01

softcode


People also ask

What is the difference between Axios and vue-Axios?

vue-axios is just a wrapper, exposing axios to components as this. axios , this. $http , or Vue. axios .

Does Axios work with vue?

Axios is a popular JavaScript library used to make HTTP requests. It is a promise-based HTTP client used in JavaScript or with other Javascript libraries like Vue.

What is the use of vue resource?

The plugin for Vue. js provides services for making web requests and handle responses using a XMLHttpRequest or JSONP.


2 Answers

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>
like image 32
Emad Adly Avatar answered Nov 15 '22 22:11

Emad Adly


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
like image 108
Nicolas Heimann Avatar answered Nov 15 '22 22:11

Nicolas Heimann