Talking About the Axios HTTP Library

· 2 min read · 309 Words · -Views -Comments

Axios is the go-to HTTP library in many front-end stacks. Here are a few nuances I’ve run into.

Axios in context

I like understanding a tool’s mission so I know its limits. Axios wraps XMLHttpRequest in the browser (and http/https in Node) to offer a friendlier API—nothing more, nothing less.

Official tagline: Promise based HTTP client for the browser and node.js

Questions I’ve bumped into

Which status codes trigger catch?

Axios resolves the promise for 200 <= status < 300; everything else rejects.

Axios source screenshot

Axios source screenshot

100-level codes aren’t common. 300-level redirects are handled transparently by the browser. Practically, you’ll see rejections for 4xx and 5xx responses.

What about xhr.onerror?

Axios wraps XHR, so let’s peek at the API. XHR exposes onload and onerror. Does a 500 trigger onerror? Nope. onerror only fires on network-layer problems (e.g., the request couldn’t be sent). 4xx and 5xx still hit onload. So Axios rejections stem from application-level status checks, not XHR onerror.

XHR docs

Does a 301 redirect refresh the whole page?

No. XHR exists to avoid full page reloads. The browser follows the redirect behind the scenes and returns the final response to your code.

Sending array parameters

One approach:

axios.defaults.paramsSerializer = params => {
  return qs.stringify(params, { arrayFormat: 'repeat' });
};

This yields URLs like https://bugs.chromium.org/p/chromium/issues/detail?id=1&id=2&id=3. Repeated keys are perfectly valid.

Why do some requests show canceled in DevTools?

That status means the front end aborted the request. XHR exposes abort():

The XMLHttpRequest.abort() method aborts the request if it has already been sent. When a request is aborted, its readyState is changed to XMLHttpRequest.UNSENT (0) and the request's status code is set to 0.

Axios calls abort() when a request exceeds the configured timeout, so DevTools lists it as canceled. Contrast that with a 504 gateway timeout, which comes from the server.

Final Thoughts

Nothing exotic here, but they’re easy details to forget—worth writing down.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover