Use Axios with and without CSRF token
Our current implementation of axios forces all axios requests to include the CSRF token to it's requests. In the code below, we override the defaults of the library and then re-export it for use later.
import axios from 'axios';
import csrf from './csrf';
axios.defaults.headers.common[csrf.headerKey] = csrf.token;
// Used by Rails to check if it is a valid XHR request
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
// Maintain a global counter for active requests
// see: spec/support/wait_for_requests.rb
axios.interceptors.request.use((config) => {
window.activeVueResources = window.activeVueResources || 0;
window.activeVueResources += 1;
return config;
});
// Remove the global counter
axios.interceptors.response.use((config) => {
window.activeVueResources -= 1;
return config;
}, (e) => {
window.activeVueResources -= 1;
return Promise.reject(e);
});
export default axios;
Since we want Axios to be the default way to do network requests on gitlab frontend, we need to determine a good setup for Axios configuration so that we can easily import Axios and perform network requests with and without CSRF tokens. We recently came across an example scenario where we did not want to include CSRF tokens.
Previous discussion about the CSRF tokens can be found in https://gitlab.com/gitlab-org/gitlab-ce/issues/39727#note_46984135
Edited by Clement Ho