HTTP requests are a crucial part of any web application that’s 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.
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’t 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.
We might also reach for libraries to help us. For Ajax, axios 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.
Installation and the basics
It can be installed using npm (or yarn):
npm install axios
An independent POST request using Axios looks like this:
axios.post('https://axios-app.firebaseio.com/users.json', formData)
.then(res => console.log(res))
.catch(error => console.log(error))
Native JavaScript has multiple ways of doing JavaScript too. Notably, fetch()
. So why use a library at all? Well, for one, error handling in fetch is pretty wonky. You’ll have a better time with axios right out of the gate with that. If you’d like to see a comparison, we have an article that covers both and an article that talks about the value of abstraction with stuff like this.
Another reason to reach for axios? It gives us more opportunities for DRYness, so let’s look into that.
Global config
We can set up a global configuration (e.g. in our main.js
file) that handles all application requests using a standard configuration that is set through a default object that ships with axios.
This object contains:
baseURL:
A relative URL that acts as a prefix to all requests, and each request can append the URLheaders
: Custom headers that can be set based on the requeststimeout:
The point at which the request is aborted, usually measured in milliseconds. The default value is0
, meaning it’s not applicable.withCredentials
: Indicates whether or not cross-site Access-Control requests should be made using credentials. The default isfalse
.responseType
: Indicates the type of data that the server will return, with options includingjson
(default),arraybuffe
r,document
,text
, andstream
.responseEncoding
: Indicates encoding to use for decoding responses. The default value isutf8
.xsrfCookieName
: The name of the cookie to use as a value for XSRF token, the default value isXSRF-TOKEN
.xsrfHeaderName
: The name of the HTTP header that carries the XSRF token value. The default value isX-XSRF-TOKEN
.maxContentLength
: Defines the max size of the HTTP response content in bytes allowedmaxBodyLength
: Defines the max size of the HTTP request content in bytes allowed
Most of time, you’ll only be using baseURL
, header
, and maybe timeout
. The rest of them are less frequently needed as they have smart defaults, but it’s nice to know there are there in case you need to fix up requests.
This is the DRYness at work. For each request, we don’t have to repeat the baseURL
of our API or repeat important headers that we might need on every request.
Here’s an example where our API has a base, but it also has multiple different endpoints. First, we set up some defaults:
/ 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))
}
}
}
Note: This example is in Vue, but the concept extends to any JavaScript situation.
Custom instance
Setting up a “custom instance” is similar to a global config, but scoped to specified components. So, it’s still a DRY technique, but with hierarchy.
We’ll set up our custom instance in a new file (let’s call it authAxios.js
) and import it into the “concern” components.
// 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'}
})
And then we import this file into the form components:
// 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
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.
Interceptors can be in the main.js
file or a custom instance file. Requests are intercepted after they’ve been sent out and allow us to change how the response is handled.
// 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);
});
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 baseURL
. 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.
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.
Interestingly, we can eject an interceptor to prevent it from having any effect at all. We’ll have to assign the interceptor to a variable and eject it using the appropriately named 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);
Although it’s less commonly used, it’s possible to put and interceptor into a conditional statement or remove one based on some event.
Hopefully this gives you a good idea about the way axios works as well as how it can be used to keep API requests DRY in an application. While we scratched the surface by calling out common use cases and configurations, axis has so many other advantages you can explore in the documentation, including the ability to cancel requests and protect against cross-site request forgery , among other awesome possibilities.
The post Stay DRY Using axios for API Requests appeared first on CSS-Tricks.
from CSS-Tricks https://ift.tt/30Wj7Ce
via IFTTT
No comments:
Post a Comment