{"id":312657,"date":"2020-06-18T08:02:25","date_gmt":"2020-06-18T15:02:25","guid":{"rendered":"https:\/\/css-tricks.com\/?p=312657"},"modified":"2020-06-22T07:47:15","modified_gmt":"2020-06-22T14:47:15","slug":"stay-dry-using-axios-for-api-requests","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/stay-dry-using-axios-for-api-requests\/","title":{"rendered":"Stay DRY Using axios for API Requests"},"content":{"rendered":"\n
HTTP requests are a crucial part of any web application that\u2019s communicating with a back-end server. The front end needs some data, so it asks for it via a network HTTP request (or Ajax, as it tends to be called), and the server returns an answer. Almost every website these days does this in some fashion.<\/p>\n\n\n\n
With a larger site, we can expect to see more of this. More data, more APIs, and more special circumstances. As sites grow like this, it is important to stay organized. One classic concept is DRY (short for Don\u2019t Repeat Yourself), which is the process of abstracting code to prevent repeating it over and over. This is ideal because it often allows us to write something once, use it in multiple places, and update in a single place rather than each instance.<\/p>\n\n\n\n
We might also reach for libraries to help us. For Ajax, axios<\/a> is a popular choice. You might already be familiar with it, and even use it for things like independent POST and GET requests while developing. <\/p>\n\n\n It can be installed using npm (or yarn):<\/p>\n\n\n\n An independent POST request using Axios looks like this:<\/p>\n\n\n\n Native JavaScript has multiple ways of doing JavaScript too. Notably, Another reason to reach for axios? It gives us more opportunities for DRYness, so let\u2019s look into that. <\/p>\n\n\n We can set up a global configuration (e.g. in our This object contains:<\/p>\n\n\n\n Most of time, you\u2019ll only be using This is the DRYness at work. For each request, we don\u2019t have to repeat the Here\u2019s an example where our API has a base, but it also has multiple different endpoints. First, we set up some defaults:<\/p>\n\n\n\n Note:<\/strong> This example is in Vue, but the concept extends to any JavaScript situation.<\/p>\n\n\n Setting up a \u201ccustom instance\u201d is similar to a global config, but scoped to specified components. So, it\u2019s still a DRY technique, but with hierarchy. <\/p>\n\n\n\n We\u2019ll set up our custom instance in a new file (let\u2019s call it And then we import this file into the form components:<\/p>\n\n\n\n Interceptors helps with cases where the global config or custom instance might be too generic, in the sense that if you set up an header within their objects, it applies to the header of every request within the affected components. Interceptors have the ability to change any object properties on the fly. For instance, we can send a different header (even if we have set one up in the object) based on any condition we choose within the interceptor.<\/p>\n\n\n\n Interceptors can be in the Interceptors, as the name implies, intercept both requests and responses to act differently based on whatever conditions are provided. For instance, in the request interceptor above, we inserted a conditional timeout only if the requests have a particular Interceptors will prove useful as your project becomes larger and you start to have lots of routes and nested routes all communicating to servers based on different triggers. Beyond the conditions I set above, there are many other situations that can warrant the use of interceptors, based on your project.<\/p>\n\n\n\n Interestingly, we can eject an interceptor to prevent it from having any effect at all. We\u2019ll have to assign the interceptor to a variable and eject it using the appropriately named Although it\u2019s less commonly used, it\u2019s possible to put and interceptor into a conditional statement or remove one based on some event.<\/p>\n\n\n\nInstallation and the basics<\/h3>\n\n\n
npm install axios<\/code><\/pre>\n\n\n\n
axios.post('https:\/\/axios-app.firebaseio.com\/users.json', formData)\n\u00a0 .then(res => console.log(res))\n\u00a0 .catch(error => console.log(error))<\/code><\/pre>\n\n\n\n
fetch()<\/code><\/a>. So why use a library at all? Well, for one, error handling in fetch is pretty wonky. You\u2019ll have a better time with axios right out of the gate with that. If you\u2019d like to see a comparison, we have an article that covers both<\/a> and an article that talks about the value of abstraction<\/a> with stuff like this.<\/p>\n\n\n\n
Global config<\/h3>\n\n\n
main.js<\/code> file) that handles all application requests using a standard configuration<\/strong> that is set through a default object that ships with axios. <\/p>\n\n\n\n
baseURL:<\/code><\/strong> A relative URL that acts as a prefix to all requests, and each request can append the URL<\/li>
headers<\/code>:<\/strong> Custom headers that can be set based on the requests<\/li>
timeout:<\/code><\/strong> The point at which the request is aborted, usually measured in milliseconds. The default value is
0<\/code>, meaning it\u2019s not applicable.<\/li>
withCredentials<\/code>:<\/strong> Indicates whether or not cross-site Access-Control requests should be made using credentials. The default is
false<\/code>.<\/li>
responseType<\/code>:<\/strong> Indicates the type of data that the server will return, with options including
json<\/code> (default),
arraybuffe<\/code>r,
document<\/code>,
text<\/code>, and
stream<\/code>.<\/li>
responseEncoding<\/code>:<\/strong> Indicates encoding to use for decoding responses. The default value is
utf8<\/code>.<\/li>
xsrfCookieName<\/code>:<\/strong> The name of the cookie to use as a value for XSRF token, the default value is
XSRF-TOKEN<\/code>.<\/li>
xsrfHeaderName<\/code>:<\/strong> The name of the HTTP header that carries the XSRF token value. The default value is
X-XSRF-TOKEN<\/code>.<\/li>
maxContentLength<\/code>: <\/strong>Defines the max size of the HTTP response content in bytes allowed<\/li>
maxBodyLength<\/code>:<\/strong> Defines the max size of the HTTP request content in bytes allowed<\/li><\/ul>\n\n\n\n
baseURL<\/code>,
header<\/code>, and maybe
timeout<\/code>. The rest of them are less frequently needed as they have smart defaults, but it\u2019s nice to know there are there in case you need to fix up requests.<\/p>\n\n\n\n
baseURL<\/code> of our API or repeat important headers that we might need on every request. <\/p>\n\n\n\n
\/\/ main.js\nimport axios from 'axios';\n\u2028\naxios.defaults.baseURL = 'https:\/\/axios-app.firebaseio.com' \/\/ the prefix of the URL\naxios.defaults.headers.get['Accept'] = 'application\/json' \u00a0 \/\/ default header for all get request\naxios.defaults.headers.post['Accept'] = 'application\/json' \u00a0\/\/ default header for all POST request\n\u2028\nThen, 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:\n\u2028\n\/\/ form.js component\nimport axios from 'axios';\n\u2028\nexport default {\n\u00a0 methods : {\n\u00a0 \u00a0 onSubmit () {\n\u00a0 \u00a0 \u00a0 \/\/ The URL is now https:\/\/axios-app.firebaseio.com\/users.json\n\u00a0 \u00a0 \u00a0 axios.post('\/users.json', formData)\n\u00a0 \u00a0 \u00a0 \u00a0 .then(res => console.log(res))\n\u00a0 \u00a0 \u00a0 \u00a0 .catch(error => console.log(error))\n\u00a0 \u00a0 }\n\u00a0 }\n}<\/code><\/pre>\n\n\n\n
Custom instance<\/h3>\n\n\n
authAxios.js<\/code>) and import it into the \u201cconcern\u201d components.<\/p>\n\n\n\n
\/\/ authAxios.js\nimport axios from 'axios'\n\u2028\nconst customInstance = axios.create ({\n\u00a0 baseURL : 'https:\/\/axios-app.firebaseio.com'\n})\ncustomInstance.defaults.headers.post['Accept'] = 'application\/json'\n\u2028\n\/\/ Or like this...\nconst customInstance = axios.create ({\n\u00a0 baseURL : 'https:\/\/axios-app.firebaseio.com',\n\u00a0 headers: {'Accept': 'application\/json'}\n})<\/code><\/pre>\n\n\n\n
\/\/ form.js component\n\u2028\n\/\/ import from our custom instance\nimport axios from '.\/authAxios'\n\u2028\nexport default {\n\u00a0 methods : {\n\u00a0 \u00a0 onSubmit () {\n\u00a0 \u00a0 \u00a0 axios.post('\/users.json', formData)\n\u00a0 \u00a0 \u00a0 .then(res => console.log(res))\n\u00a0 \u00a0 \u00a0 .catch(error => console.log(error))\n\u00a0 \u00a0 }\n\u00a0 }\n}<\/code><\/pre>\n\n\n
Interceptors<\/h3>\n\n\n
main.js<\/code> file or a custom instance file. Requests are intercepted after they\u2019ve been sent out and allow us to change how the response is handled.<\/p>\n\n\n\n
\/\/ Add a request interceptor\naxios.interceptors.request.use(function (config) {\n\u00a0 \/\/ Do something before request is sent, like we're inserting a timeout for only requests with a particular baseURL\n\u00a0 if (config.baseURL === 'https:\/\/axios-app.firebaseio.com\/users.json') {\u00a0\n\u00a0 \u00a0 config.timeout = 4000\u00a0\n\u00a0 } else {\u00a0\n\u00a0 \u00a0 return config\n\u00a0 }\n\u00a0 console.log (config)\n\u00a0 \u00a0 return config;\n\u00a0 }, function (error) {\n\u00a0 \/\/ Do something with request error\n\u00a0 return Promise.reject(error);\n});\n\u00a0\n\/\/ Add a response interceptor\naxios.interceptors.response.use(function (response) {\n\u00a0 \/\/ 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 \u00a0\n\u00a0 if (response.status === 200 || response.status 201) {\n\u00a0 \u00a0 router.replace('homepage') }\n\u00a0 else {\n\u00a0 \u00a0 alert('Unusual behaviour')\n\u00a0 }\n\u00a0 console.log(response)\n\u00a0 return response;\n}, function (error) {\n\u00a0 \/\/ Do something with response error\n\u00a0 return Promise.reject(error);\n});<\/code><\/pre>\n\n\n\n
baseURL<\/code>. For the response, we can intercept it and modify what we get back, like change the route or have an alert box, depending on the status code. We can even provide multiple conditions based on different error codes.<\/p>\n\n\n\n
eject<\/code> method.<\/p>\n\n\n\n
const reqInterceptor = axios.interceptors.request.use(function (config) {\n\u00a0 \/\/ Do something before request is sent, like we're inserting a timeout for only requests with a particular baseURL\n\u00a0 if (config.baseURL === 'https:\/\/axios-app.firebaseio.com\/users.json') {\n\u00a0 \u00a0 config.timeout = 4000\n\u00a0 } else {\n\u00a0 \u00a0 return config\n\u00a0 }\n\u00a0 console.log (config)\n\u00a0 return config;\n}, function (error) { \u00a0 \u00a0\n\u00a0 \/\/ Do something with request error\n\u00a0 return Promise.reject(error);\n});\n\u00a0\n\/\/ Add a response interceptor\nconst resInterceptor = axios.interceptors.response.use(function (response) {\n\u00a0 \/\/ 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 \u00a0\n\u00a0 if (response.status === 200 || response.status 201) {\n\u00a0 \u00a0 router.replace('homepage')\n\u00a0 } else {\n\u00a0 \u00a0 alert('Unusual behaviour')\n\u00a0 }\n\u00a0 console.log(response)\n\u00a0 return response;\n}, function (error) {\n\u00a0 \/\/ Do something with response error\n\u00a0 return Promise.reject(error);\n});\n\u2028\naxios.interceptors.request.eject(reqInterceptor);\naxios.interceptors.request.eject(resInterceptor);<\/code><\/pre>\n\n\n\n
\n\n\n\n