Member-only story
If you search for libraries to make API calls from Node.js, chances are you’ll run into the Axios package. It’s easy to use, well documented, uses promises, and it works in browsers too.
When things go wrong
The main complaint from other developers is that when they make a request and an error response is returned, it’s not obvious how to get information about the error. Usually, this happens when they don’t catch the exception and expect the response to include the status code.
const response = await axios.get(SOME_URL);
if(response.status === 404) {
console.error(`${SOME_URL} not found!`);
}
This approach won’t work because Axios, by default, throws an exception for any status code that isn’t 2xx. There is a workaround though.
Making it more responsive
You can tell Axios that you want to see every response regardless of if it’s an error or not using the request options. You need to provide a validateStatus
method that always returns true
. This method is passed to Axios in the request options.
const response = await axios.get(SOME_URL, {
validateStatus: () => true,
});
if(response.status === 404) {
console.error(`${SOME_URL} not found!`);
}