Skip to content

Instantly share code, notes, and snippets.

@unr
Created March 21, 2017 15:01
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 15 You must be signed in to fork a gist
  • Save unr/32a4b52192dd3507025603aa75e38970 to your computer and use it in GitHub Desktop.
Save unr/32a4b52192dd3507025603aa75e38970 to your computer and use it in GitHub Desktop.
Simplistic Axios in VueJs Example
const axiosconfig = {
baseurl: 'https://site.com/api/',
timeout: 30000,
};
import Vue from 'vue';
import axios from 'axios';
// Setting up Axios on Vue Instance, for use via this.$axios
Vue.prototype.$axios = axios.create(axiosConfig);
// Default vars set up from localStorage (ie, user has come back)
Vue.prototype.$axios.defaults.headers.common.Authorization = `Bearer ${localStorage.getItem('id_token')}`;
Vue.prototype.$axios.defaults.headers.common['Access-Token'] = localStorage.getItem('auth_token');
// Example app starts up, uses axios to collect posts.
new Vue({
mounted() {
this.$axios.get('/posts').then((response) => {
this.posts = response.data;
}).catch((err) => {
console.log(err);
});
},
});
@bdelaney
Copy link

bdelaney commented Dec 14, 2017

Is there any reason this will not work in a Vue project using Webpack?
I'm in dev run mode and this.$axios is coming back as localhost:8080 instead of the baseurl I configured, and XHR error due to no match on baseurl.
Trying to use with OAuth2 token directly pasted into the Authorization value.

Console error: HTTP404: NOT FOUND - The server has not found anything matching the requested URI (Uniform Resource Identifier).
(XHR)GET - http://localhost:8080/accounts

I have not set up vue-router yet. Maybe that explains it.

@marco-carvalho
Copy link

i got an error because "baseurl" should be "baseURL"

@alant
Copy link

alant commented Mar 30, 2018

change const axiosconfig to const axiosConfig?

@LyleScott
Copy link

Awesome, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment