Axios

1. How to instal

  • npm
npm i axios
  • cdn
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.0.0-alpha.1/axios.min.js"></script>

2. GET REQUEST

  • Fetch Data
const res = await axios.get("URL"); <!-- "get data"--> console.log(res.data); <!-- "get response" state --> console.log(res.status);
  • Catch Errors
axios.get("URL") .then(() => {}) .catch(error => {console.log(error)});

Example

// fetch posts from jsonplaceholder API via Axios axios.get("https://jsonplaceholder.typicode.com/posts") .then(res => console.log(res.data)) .catch(error => console.log(error))

3. POST REQUEST

  • Send Data With Post Method
axios.post("URL" , {"the object that you want to send"});

Example

// send new data into jsonplaceholder api via POST method axios.post("https://jsonplaceholder.typicode.com/posts", { title: "test title", body: "this is post body" }).then(res => console.log(res.data)) .catch(error => console.log(error));

4. PATCH REQUEST VS PUT REQUEST

what is the difrent between PATCH and PUT?

PATCH: update only data parts that are included in an object that we sent.
PUT: replace old data with the new one.

5. PATCH REQUEST

axios.patch("URL" , {"object contains only the new values"});

Example

// update todo title and complete state axios.patch("https://jsonplaceholder.typicode.com/todos/1", { "title": "todo after update all field", "completed": true }).then(res => console.log(res.data)) .catch(error => console.log(error));

6. PUT REQUEST

axios.put("URL" , {"new object values"});

Example

// replace objecct 1 in todo list axios.put("https://jsonplaceholder.typicode.com/todos/1", { "userId": 2, "id": 1, "title": "todo after update all field", "completed": true }).then(res => console.log(res.data)) .catch(error => console.log(error));

7. DELETE REQUEST

axios.delete("URL");

Example

// delete todo in url https://jsonplaceholder.typicode.com/todos/1 axios.delete("https://jsonplaceholder.typicode.com/todos/1") .then(res => console.log(res)) .catch(error => console.log(error));

8. SEND MORE THAN ONE REQUEST

axios.all([ axios.get("URL1"), axios.get("URL2") ]).then(axios.spread((url1Res , url2Res) => console.log(url1Res , url2Res)));

Example

// more than one request axios.all([ axios.get("https://jsonplaceholder.typicode.com/posts"), axios.get("https://jsonplaceholder.typicode.com/todos") ]).then(axios.spread((posts, todos) => console.log(posts, todos)));

9. Custom Headers

when you need to use custom headers?
example: when the api need authentication

axios.get("URL" , { headers:{ KEY:`${API_KEY}` }, params:{"Params to send for the API with request"} })

Example

axios.get("https://tomtom/api/location" , { headers:{ KEY:`${process.env.TOMTOM_DEVELOPER_KEY}` }, params:{ lat:34.25, lng:32.21 } })