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?
vue-axios is just a wrapper, exposing axios to components as this. axios , this. $http , or Vue. axios .
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.
The plugin for Vue. js provides services for making web requests and handle responses using a XMLHttpRequest or JSONP.
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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With