B
B
Bogdan2018-03-14 12:20:19
Vue.js
Bogdan, 2018-03-14 12:20:19

Wrapper for axios?

Hello. Please tell me the best way to implement a wrapper for axios: import it into each component, write eventBus, Vuex, or shove it into the Vue prototype.
Vuex seems to suit me, but how it turns out and I import some variables from Vuex into the http wrapper, and then I import the http.js wrapper
into Vuex

import axios from 'axios';

import store from '@/store';

console.log( store )

export const http = axios.create( {
  baseURL: store.state.apiUrl,
  timeout: 1000,
  headers: { 'Authorization': `Bearer ${ store.state.accessToken }` }
} );

store.js
import Vue from 'vue';
import Vuex from 'vuex';

import { http } from './http';

and an error appears
http.js?31b3:8 Uncaught TypeError: Cannot read property 'state' of undefined

Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan, 2018-03-14
@LiguidCool

In principle, you can import into each component, especially as far as I know in reality it will import only once.
However, in the same Laravel.Mix, if memory serves, Axios is attached to window , i.e. just becomes global. Of course, I understand that "You can't pollute the global space and ko-ko-ko ...", but JQuery, loadash, Axios and the like are an exception to the rule.
Basically the same as c window . If you don’t need Vue and Axios everywhere without it, you can do it that way.

M
markmariner, 2018-03-16
@markmariner

You don't need to create a separate http.js wrapper
Import axios in store.js and set the defaults:

import axios from 'axios'

axios.defaults.baseURL = ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question