Front-end code that talks to a back end accumulates HTTP requests fast: more APIs, more payloads, more special cases. The DRY principle (Don't Repeat Yourself) is the usual answer — abstract the repeated work so it lives in one place and changes there once. For Ajax, axios is a common library choice, and it offers several layers at which that abstraction can happen.

Setup

Installing axios is a one-liner with npm or yarn:

npm install axios

A standalone POST request looks like this:

axios.post('https://axios-app.firebaseio.com/users.json', formData)
  .then(res => console.log(res))
  .catch(error => console.log(error))

JavaScript's native fetch() is an alternative, but error handling in fetch is awkward, and axios gives a smoother experience from the start.

Application-wide defaults

Axios ships with a default configuration object. Setting it once (in main.js, for example) applies a standard configuration to every request the application makes. The object's properties:

  • baseURL: a relative URL used as a prefix for all requests, with each request appending its own path
  • headers: custom headers to send with requests
  • timeout: the point at which a request is aborted, usually in milliseconds; defaults to 0, meaning no timeout applies
  • withCredentials: whether cross-site Access-Control requests are made with credentials; defaults to false
  • responseType: the type of data the server returns — json (default), arraybuffer, document, text, or stream
  • responseEncoding: encoding used to decode responses; defaults to utf8
  • xsrfCookieName: the cookie holding the XSRF token value; defaults to XSRF-TOKEN
  • xsrfHeaderName: the HTTP header carrying the XSRF token; defaults to X-XSRF-TOKEN
  • maxContentLength: maximum allowed size of the HTTP response content in bytes
  • maxBodyLength: maximum allowed size of the HTTP request content in bytes

In practice you'll mostly touch baseURL, header and perhaps timeout; the rest have sensible defaults and are rarely needed. The payoff is that no individual request has to repeat the API's base URL or the headers every call requires. Below, a base URL is set once even though the API exposes several endpoints (the example is Vue, but the pattern applies to any JavaScript codebase):

// main.js
import axios from 'axios';


axios.defaults.baseURL = 'https://axios-app.firebaseio.com' // the prefix of the URL
axios.defaults.headers.get['Accept'] = 'application/json'   // default header for all get request
axios.defaults.headers.post['Accept'] = 'application/json'  // default header for all POST request


Then, in a component, we can use axios more succinctly, not needing to set those headers, but still having an opportunity to customize the final URL endpoint:


// form.js component
import axios from 'axios';


export default {
  methods : {
    onSubmit () {
      // The URL is now https://axios-app.firebaseio.com/users.json
      axios.post('/users.json', formData)
        .then(res => console.log(res))
        .catch(error => console.log(error))
    }
  }
}

Scoped instances

A custom instance works like a global config but is scoped to particular components — DRY with a hierarchy. Create it in its own file (here, authAxios.js) and import it wherever it's needed:

// authAxios.js
import axios from 'axios'


const customInstance = axios.create ({
  baseURL : 'https://axios-app.firebaseio.com'
})
customInstance.defaults.headers.post['Accept'] = 'application/json'


// Or like this...
const customInstance = axios.create ({
  baseURL : 'https://axios-app.firebaseio.com',
  headers: {'Accept': 'application/json'}
})

The consuming form components then import that file:

// form.js component


// import from our custom instance
import axios from './authAxios'


export default {
  methods : {
    onSubmit () {
      axios.post('/users.json', formData)
      .then(res => console.log(res))
      .catch(error => console.log(error))
    }
  }
}

Interceptors

Global config and custom instances can be too broad: a header set there applies to every request in the affected components. Interceptors change any object property on the fly, so a conditional check inside one can send a different header even when the object already defines one. They live either in main.js or in a custom instance file. Requests are intercepted after they've been sent out, and the response handling can be rewritten as well.

// Add a request interceptor
axios.interceptors.request.use(function (config) {
  // Do something before request is sent, like we're inserting a timeout for only requests with a particular baseURL
  if (config.baseURL === 'https://axios-app.firebaseio.com/users.json') { 
    config.timeout = 4000 
  } else { 
    return config
  }
  console.log (config)
    return config;
  }, function (error) {
  // Do something with request error
  return Promise.reject(error);
});
 
// Add a response interceptor
axios.interceptors.response.use(function (response) {
  // Do something with response data like console.log, change header, or as we did here just added a conditional behaviour, to change the route or pop up an alert box, based on the reponse status  
  if (response.status === 200 || response.status 201) {
    router.replace('homepage') }
  else {
    alert('Unusual behaviour')
  }
  console.log(response)
  return response;
}, function (error) {
  // Do something with response error
  return Promise.reject(error);
});

Both requests and responses pass through interceptors, which act on whatever conditions you supply. In the request interceptor above, a timeout is applied only when the request's baseURL matches a particular value. On the response side, you can alter what comes back — redirect to another route or show an alert box depending on the status code — and multiple conditions can be keyed to different error codes. This matters as a project grows and many routes and nested routes trigger server communication from different places.

An interceptor can also be ejected so it has no effect at all. Assign it to a variable and call the eject method:

const reqInterceptor = axios.interceptors.request.use(function (config) {
  // Do something before request is sent, like we're inserting a timeout for only requests with a particular baseURL
  if (config.baseURL === 'https://axios-app.firebaseio.com/users.json') {
    config.timeout = 4000
  } else {
    return config
  }
  console.log (config)
  return config;
}, function (error) {    
  // Do something with request error
  return Promise.reject(error);
});
 
// Add a response interceptor
const resInterceptor = axios.interceptors.response.use(function (response) {
  // Do something with response data like console.log, change header, or as we did here just added a conditional behaviour, to change the route or pop up an alert box, based on the reponse status  
  if (response.status === 200 || response.status 201) {
    router.replace('homepage')
  } else {
    alert('Unusual behaviour')
  }
  console.log(response)
  return response;
}, function (error) {
  // Do something with response error
  return Promise.reject(error);
});


axios.interceptors.request.eject(reqInterceptor);
axios.interceptors.request.eject(resInterceptor);

The less common use: placing an interceptor inside a conditional, or removing one in response to an event.

The axios documentation covers further capabilities beyond these common configurations, including request cancellation and cross-site request forgery protection.