doc/development/fe_guide/axios.md
In older parts of our codebase using the REST API, we used Axios to communicate with the server, but you should not use Axios in new applications. Instead rely on apollo-client to query the GraphQL API. For more details, see our GraphQL documentation.
To guarantee all defaults are set you should import Axios from axios_utils. Do not use Axios directly.
All our requests require a CSRF token.
To guarantee this token is set, we are importing Axios, setting the token, and exporting axios .
This exported module should be used instead of directly using Axios to ensure the token is set.
import axios from './lib/utils/axios_utils';
axios.get(url)
.then((response) => {
// `data` is the response that was provided by the server
const data = response.data;
// `headers` the headers that the server responded with
// All header names are lower cased
const paginationData = response.headers;
})
.catch(() => {
//handle the error
});
To help us mock the responses we are using axios-mock-adapter.
Advantages over spyOn():
replyOnce() to allow for different responsesWe have also decided against using Axios interceptors because they are not suitable for mocking.
import axios from '~/lib/utils/axios_utils';
import MockAdapter from 'axios-mock-adapter';
let mock;
beforeEach(() => {
// This sets the mock adapter on the default instance
mock = new MockAdapter(axios);
// Mock any GET request to /users
// arguments for reply are (status, data, headers)
mock.onGet('/users').reply(200, {
users: [
{ id: 1, name: 'John Smith' }
]
});
});
afterEach(() => {
mock.restore();
});
Because a polling function requires a header object, we need to always include an object as the third argument:
mock.onGet('/users').reply(200, { foo: 'bar' }, {});