Last active
October 2, 2021 16:07
-
-
Save dbshoupe/2c52a8145fbf811b8b7f1408f7be1858 to your computer and use it in GitHub Desktop.
Wrapper class for Axios in a Vue project that uses interceptor to inject token (stored using Vuex) into header for each request.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios from 'axios'; | |
import store from "@/data/state" | |
class Http { | |
constructor() { | |
let service = axios.create({}); | |
service.interceptors.request.use((config) => { | |
config.headers.common['x-access-token'] = store.state.token | |
return config | |
}) | |
this.service = service; | |
} | |
redirectTo = (document, path) => { | |
document.location = path | |
} | |
get(path) { | |
return this.service.get(path) | |
} | |
patch(path, payload, callback) { | |
return this.service.request({ | |
method: 'PATCH', | |
url: path, | |
responseType: 'json', | |
data: payload | |
}).then((response) => callback(response.status, response.data)); | |
} | |
post(path, payload) { | |
return this.service.request({ | |
method: 'POST', | |
url: path, | |
responseType: 'json', | |
data: payload | |
}) | |
} | |
} | |
export default new Http; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thx for this little piece of code. It helped me a lot to understand the workings of Vuejs.
But I have a problem which I do not get my head around: I implemented this wrapper and imported it as a plugin. I further added this
.then(...
line to the post method, because this is what I need for my program. However, it always reports me thatcallback
is undefined. Why is it? And how would I solve it? It would be great if you could shed some light on this. Thx!This is my wrapper code:
and this the caller: