Axios

Michael Minchang Kim·2020년 7월 14일
0

Installing Axios

npm i axios

What is Axios?

Axios is a "promise based HTTP client for the browser and node.js"

So what does this mean? What is a promise and what does a HTTP client do?

Promise

A promise is used to handle asynchronous operations without the use of callback functions.
With callback functions, operations have to be nested within each other.
( So called Callback Hell)

              doSomething(function(result) {                
                doSomethingElse(result, function(newResult) {
                  doThirdThing(newResult, function(finalResult) {
                    console.log('Got the final result: ' + finalResult);
                  }, failureCallback);
                }, failureCallback);
              }, failureCallback);

Promises allow for a cleaner code by using .then.

              doSomething()
              .then(function(result) {
                return doSomethingElse(result);
              })
              .then(function(newResult) {
                return doThirdThing(newResult);
              })
              .then(function(finalResult) {
                console.log('Got the final result: ' + finalResult);
              })
              .catch(failureCallback);

HTTP Client

A HTTP Client simply handles the HTTP requests and the responses.
*More info on HTTP Requests on previous post.

Why Axios?

What is the benefit of using axios over fetch?
Axios allows you to create new instances of axios using custom configuration using the .create() method.

This allows for a highly effective way to organize all the API requests within a project.

By creating one file or folder that contains all the custom Axios and exporting it,
you can add, remove, edit, refactor all in one place.

Creating an axios instance

You can create an instance by using axios.create() and feeding the method a custom configuration in the form of an object.

		const apiUrl = 'https://some-domain.com'
                
                const authAxios = axios.create({
                    baseURL: `${apiUrl}API`,
                    timeout: 1000,
                    headers: {
                      Authorization: `Token ${accessToken}`,
                    },
                  });

Using an axios instance

                authAxios
                  .get("/1/kanban/")
                  .then((res) => console.log("res", res.data))
                  .catch((err) => console.log(err));

Using .get() allows you to add additional endpoints, url parameters, or querystrings to the preset baseURL.
.then() is equal to the one in fetch except for the fact that you do not have to change the response from json format.
.catch() handles errors since axios is a promise.

profile
Soon to be the world's Best programmer ;)

0개의 댓글