axios_utils.js 1.03 KB
Newer Older
1 2 3
import axios from 'axios';
import csrf from './csrf';

4
axios.defaults.headers.common[csrf.headerKey] = csrf.token;
5 6
// Used by Rails to check if it is a valid XHR request
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
7 8 9

// Maintain a global counter for active requests
// see: spec/support/wait_for_requests.rb
Mike Greiling's avatar
Mike Greiling committed
10
axios.interceptors.request.use(config => {
11 12
  window.pendingRequests = window.pendingRequests || 0;
  window.pendingRequests += 1;
13 14 15 16
  return config;
});

// Remove the global counter
Mike Greiling's avatar
Mike Greiling committed
17
axios.interceptors.response.use(
18
  response => {
19
    window.pendingRequests -= 1;
20
    return response;
Mike Greiling's avatar
Mike Greiling committed
21
  },
22
  err => {
23
    window.pendingRequests -= 1;
24
    return Promise.reject(err);
Mike Greiling's avatar
Mike Greiling committed
25 26
  },
);
27 28

export default axios;
29 30 31 32 33 34 35 36

/**
 * @return The adapter that axios uses for dispatching requests. This may be overwritten in tests.
 *
 * @see https://github.com/axios/axios/tree/master/lib/adapters
 * @see https://github.com/ctimmerm/axios-mock-adapter/blob/v1.12.0/src/index.js#L39
 */
export const getDefaultAdapter = () => axios.defaults.adapter;