Notes on using Axios on frontend/browser

Note: This post is a details-post for the post: Learning web app development through free online tutorials – Organized Notes and Log, https://raviswdev.blogspot.com/2024/03/learning-web-app-development-through.html .

This section is about using Axios on frontend/browser (and not node.js backend)

https://axios-http.com/docs/example has a minimal example but it is for node.js. However after above script line is inserted in browser side code (html file), similar code to the node.js example works except that we don't need the initial require statement.

---Needed code start---
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .finally(function () {
    // always executed
  });
---Needed code end---

The code I used in my test html file:

    https://unpkg.com/axios/dist/axios.min.js
    <script>
      let frm = document.getElementById("frm");
      let divusers = document.getElementById("div-users");
...
      getUsers();
      function getUsers() {
        axios
          .get("/api/people")
          // .get("/api/peoplex") //To test error handling; error handling works (goes to catch)
          .then(function (res) {
            // handle success
            console.log(res);
            let people = res.data.data;
            console.log(people);
            people.forEach((person) => {
              divusers.innerHTML += " " + person.name;
            });
          })
          .catch(function (error) {
            // handle error
            console.log("In catch");
            console.log(error);
          });
      }
    </script>
  </body>
</html>
--- end code from my test html file ---

Axios: accessing data of response for JSON post – see “Axios POST JSON request” in Axios tutorial, https://zetcode.com/javascript/axios/ . Alternatively see “Forms” in POST Requests, https://axios-http.com/docs/post_example

Key point is that await axios.post returns a response object and the JSON data of the response is put in response.data. So the typical statement is:

const { data } = await axios.post("/api/people", {
// object data sent to server as name:value pairs
          });

console.log(data); //Prints out the JSON data sent in response from server 

...

How to Use Axios in React [Beginners Guide 2023], https://www.upgrad.com/blog/axios-in-react/

Comments

Archive