Axios vs Fetch
Hello guys, sorry to disturb you all; I was just reading a bit about the difference between axios and fetch. From what I have understood, some of the differences is that axios already parse the data in the respond body and so we don't have to manually use something like response.json(). Similarly, when using post requests, axios don't need to include the JSON.stringify() method. By default it already does it. It also has some other benefits like a timeout argument which fetch doesn't have (I think).
My question is, I came across the term "interceptors". I read a bit about it, from what I have understood, it's just something use to modify the request before it is send or modify the response before it is sent back. But I didn't really understand why are interceptors used or why do we need it . Can someone explain please
8 Replies
imagine that you have to always send an api key
with an interceptor, you can just add the key to the request, either as an header or as a value, depending on the api
imagine having to always manually add that in every single request all over the page/app
with an interceptor, you can set it up to just send the key on all requests and not worry about it
also, if you don't use an interceptor, and do it everything manually, you may forget to do it for a single request
and then you have to figure out why it isn't working
in simple analogy:
Like lets say you have to go to supermarket for buying some grocery for you and your friend.
While going out, your friend "intercepts" or "stops" you for a quick addition of an item to the grocery list.
and everytime you go shopping, your friend stops you for the same addition
ohhh, in my project, I needed to implement the use of sessions. Now I should have included the idea of session time out. The thing is I did that at the very last end when I already have use x number of fetch statement and so I should modify the logic of "if server responds with a specific error which indicates server timed out, then do that..."
Since I needed to include that if statement logic in every fetch, with an interceptor we could have done it only once ?
yep I see
what are interceptors important ? what if we don't use them ? how would the work be more tedious ?
sessions should timeout automatically on the server side
yep but the thing is when we would send a request, we would obtain an error, based on that error, we would trigger a specific logic
I already make use of say x number of fetch, I didn't include the logic of handling a specific error respond ;c
i think an interceptor could be used for that
yeah, at that moment, I never thought of that, I should try