In my Vue.js app, I am utilizing Axios to consume a REST API. Each time I make an API call, I create a new instance of Axios with the necessary authentication headers by calling axios.get in various places.
// UserdataComponent.vue
const anInstance = axios.create({
headers: {'X-API-TOKEN': store.state.token},
auth: {
username: SOME_USERNAME,
password: SOME_PASSWORD
}
})
anInstance.get(API_BASE_URL + '/userdata')
This process is repeated throughout my codebase whenever a REST API call is made.
To optimize and keep the code DRY (Don't Repeat Yourself), I decided to move the axios instance creation logic to a separate file.
I transferred the axios instance creation code to a separate file and attempted to export it as an object. This exported object could then be imported wherever needed for consuming the REST API.
// http.js
import axios from 'axios'
import store from 'store/store.js'
const HTTP = axios.create({
baseURL: API_BASE_URL,
headers: { 'X-API-TOKEN': store.state.token },
auth: {
username: SOME_USERNAME,
password: SOME_PASSWORD
}
})
export default HTTP
// UserdataComponent.vue
import HTTP from 'http.js'
...
HTTP.get('/userdata')
However, this approach resulted in errors, with axios.create
being interpreted as a string rather than a callable function.
What adjustments should I make to achieve the desired outcome? Is this method of modularizing the HTTP request mechanism appropriate?