logoalt Hacker News

zdragnartoday at 5:34 AM6 repliesview on HN

There are pretty much two usage patterns that come up all the time:

1- automatically add bearer tokens to requests rather than manually specifying them every single time

2- automatically dispatch some event or function when a 401 response is returned to clear the stale user session and return them to a login page.

There's no reason to repeat this logic in every single place you make an API call.

Likewise, every response I get is JSON. There's no reason to manually unwrap the response into JSON every time.

Finally, there's some nice mocking utilities for axios for unit testing different responses and error codes.

You're either going to copy/paste code everywhere, or you will write your own helper functions and never touch fetch directly. Axios... just works. No need to reinvent anything, and there's a ton of other handy features the GP mentioned as well you may or may not find yourself needing.


Replies

arghwhattoday at 8:20 AM

Interceptors are just wrappers in disguise.

    const myfetch = async (req, options) => {
        let options = options || {};
        options.headers = options.headers || {};
        options.headers['Authorization'] = token;
    
        let res = await fetch(new Request(req, options));
        if (res.status == 401) {
            // do your thing
            throw new Error("oh no");
        }
        return res;
    }
Convenience is a thing, but it doesn't require a massive library.
show 3 replies
rjmunrotoday at 10:29 AM

> Likewise, every response I get is JSON.

fetch responses have a .json() method. It's literally the first example in MDN: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/U...

It's literally easier than not using JSON because I have to think about if I want `repsponse.text()` or `response.body()`.

abluecloudtoday at 10:37 AM

that's such a weak argument. you can write about 20 lines of code to do exactly this without requiring a third party library.

anon7000today at 6:03 AM

Helper functions seem trivial and not like you’re reimplementing much.

show 1 reply
sayamqazitoday at 6:21 AM

> usage patterns

IMO interceptors are bad. they hide what might get transformed with the API call at the place it is being used.

> Likewise, every response I get is JSON. There's no reason to manually unwrap the response into JSON every time.

This is not true unless you are not interfacing with your own backends. even then why not just make a helper that unwraps as json by default but can be passed an arg to parse as something else

hiccuphippotoday at 12:44 PM

One more use case for Axios is it automatically follows redirects, forwarding headers, and more importantly, omiting or rewriting the headers that shouldn't be forwarded for security reasons.

show 1 reply