JS HTTP Request using Axios POST and GET Method Tutorial

In this tutorial, I will show how to use JS HTTP Request using Axios POST and GET Methods. The tutorial aims to provide IT/CS students and new programmers with a reference to learn with to enhance their knowledge and skill using JavaScript and Axios. Here, the step-by-step tutorial with snippets of implementing HTTP Requests using Axios is provided. A sample web application source code that demonstrates the objective of this tutorial is also provided and the source code zip file is free to download.

What is Axios?

A promise-based HTTP Client for the browser and node.js is called Axios. It can run in both a browser and Node.js using the same code because it is isomorphic. The client (browser) uses XMLHttpRequests, whereas the server uses the built-in node.js HTTP module.

How to use Axios POST and GET Methods?

To use Axios POST and GET Methods, the first thing you must do is install the package or load the Axios script using CDN.

Installing Axios

  1. /**
  2. * Using NPM
  3. */
  4.  
  5. $ npm install axios
  6.  
  7. /**
  8. * Using Yarn
  9. */
  10.  
  11. $ yarn add axios
  12.  
  13. /**
  14. * Using Bower
  15. */
  16.  
  17. $ bower install axios

Using CDN

  1. <!-- Using JSDelivr CDN -->
  2. <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  3.  
  4. <!-- Using unpkg CDN -->
  5. <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Axios POST Method syntax

The below snippets demonstrate the syntax of how to implement or execute the Axios Post Method.

  1. /**
  2. * Axios Post Method : Syntax Example 1
  3. */
  4.  
  5. axios({
  6. method: 'post',
  7. url: 'yourapiurlhere.php',
  8. headers:{
  9. 'Content-Type' : 'application/x-www-form-urlencode'
  10. },
  11. data:{
  12. 'name': 'Claire Blake',
  13. 'email' : '[email protected]'
  14. }
  15. }).then( response =>{
  16. //Request's Response
  17. console.log(response)
  18. } ).catch( error =>{
  19. // Catch Request's Error
  20. console.error(error)
  21. } )
  22.  
  23. /**
  24. * Axios Post Method : Syntax Example 2
  25. */
  26. var data = new FormData();
  27. data.append('name', 'Claire Blake')
  28. data.append('email', '[email protected]')
  29.  
  30. axios.post('yourapiurlhere.php', {
  31. headers:{
  32. 'content-type' : 'application/x-www-form-urlencode'
  33. }
  34. }).then( response =>{
  35. //Request's Response
  36. console.log(response)
  37. } ).catch( error =>{
  38. // Catch Request's Error
  39. console.error(error)
  40. } )

Axios GET Method syntax

The below snippets demonstrate the syntax of how to implement or execute the Axios GET Method.

  1. /**
  2. * Axios Post Method : Syntax Example 1
  3. */
  4.  
  5. axios({
  6. method: 'get',
  7. url: 'test.json',
  8. responseType:'json'
  9. }).then( response =>{
  10. //Request's Response
  11. console.log(response)
  12. } ).catch( error =>{
  13. // Catch Request's Error
  14. console.error(error)
  15. } )
  16.  
  17.  
  18. /**
  19. * Axios Post Method : Syntax Example 2
  20. */
  21.  
  22. axios.post('test.json', {
  23. responseType:'json'
  24. }).then( response =>{
  25. //Request's Response
  26. console.log(response)
  27. } ).catch( error =>{
  28. // Catch Request's Error
  29. console.error(error)
  30. } )
  31.  
  32. /**
  33. * Axios Post Method : Syntax Example 3
  34. */
  35.  
  36. axios('data.json').then( response =>{
  37. //Request's Response
  38. console.log(response)
  39. } ).catch( error =>{
  40. // Catch Request's Error
  41. console.error(error)
  42. } )
  43.  

Example

The snippets that I have provided below are the scripts for a simple actual web application that demonstrates the Axios GET and POST Methods. Try to copy the snippets on your end to test it on your side.

Interface

The snippet below is the page interface of the application which contains a simple interface with a navbar, buttons, and a response field. The script loads the Axios and Bootstrap Framework using CDN. Save this file as index.html.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="UTF-8">
  4. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>JS HTTP Request using Axios</title>
  7. <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
  8. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  9. <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/js/all.min.js" integrity="sha512-naukR7I+Nk6gp7p5TMA4ycgfxaZBJ7MO5iC3Fp6ySQyKFHOGfpkSZkYVWV5R7u7cfAicxanwYQ5D1e17EfJcMA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  10. <script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI=" crossorigin="anonymous"></script>
  11. <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  12. <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.2.0/axios.min.js" integrity="sha512-OdkysyYNjK4CZHgB+dkw9xQp66hZ9TLqmS2vXaBrftfyJeduVhyy1cOfoxiKdi4/bfgpco6REu6Rb+V2oVIRWg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
  13. html, body{
  14. min-height:100%;
  15. width:100%;
  16. }
  17. tbody:empty:after{
  18. content:'No records found'
  19. }
  20. </style>
  21. </head>
  22. <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
  23. <div class="container">
  24. <a class="navbar-brand" href="./">JS HTTP Request using Axios</a>
  25.  
  26. <div>
  27. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  28. </div>
  29. </div>
  30. </nav>
  31. <div class="container-fluid px-5 my-3" >
  32. <div class="col-lg-5 col-md-7 col-sm-12 mx-auto">
  33. <h3 class="text-center"><b>Axios POST and GET Method</b></h3>
  34. <div class="d-flex w-100 justify-content-center">
  35. <hr class="w-50">
  36. </div>
  37. <div class="card rounded-0 shadow mb-3">
  38. <div class="card-body">
  39. <div class="container-fluid">
  40. <div class="mb-3">
  41. <div class="d-flex justify-content-center">
  42. <button class="btn btn-primary rounded-pill col-lg-3 col-md-5 col-sm-12 me-2" id="GetBtn">Get</button>
  43. <button class="btn btn-info rounded-pill col-lg-3 col-md-5 col-sm-12 me-2" id="PostBtn">Post</button>
  44. </div>
  45. </div>
  46. <hr>
  47. <label for="" class="form-label">Response</label>
  48. <pre id="response-field" class="bg-dark p-3 text-light">
  49.  
  50. </pre>
  51. </div>
  52. </div>
  53. </div>
  54. </div>
  55. </div>
  56. </body>
  57. <script src="./script.js"></script>
  58. </html>

Sample JSON Data

The following snippet is a sample JSON Data that will be used for fetching the data on the application using the Axios GET Method. Save the file as data.json

  1. [
  2. {
  3. "name": "Ella Daniel",
  4. "email": "hendrerit.consecte[email protected]",
  5. "phone": "(567) 380-9992"
  6. },
  7. {
  8. "name": "Melyssa Cantrell",
  9. "email": "[email protected]",
  10. "phone": "1-526-413-2563"
  11. },
  12. {
  13. "name": "Chaim Buchanan",
  14. "email": "[email protected]",
  15. "phone": "1-316-685-9786"
  16. },
  17. {
  18. "name": "Desiree Welch",
  19. "email": "[email protected]",
  20. "phone": "(591) 884-4171"
  21. },
  22. {
  23. "name": "Hu Ward",
  24. "email": "[email protected]",
  25. "phone": "(858) 403-3635"
  26. }
  27. ]

Sample Post API

The snippet below is the sample PHP script that serves as an API that receives post data and returns the POST Data as the response data of the HTTP Request. Save the file post-api.php.

  1. <?php
  2.  
  3. if($_SERVER['REQUEST_METHOD'] == "POST"){
  4. echo json_encode($_POST);
  5. }else{
  6. echo json_encode(['error' => 'Request is not a POST Method']);
  7. }

Creating the Main Script

Here's the snippet of the main script that achieves our objective for this tutorial. It is a JavaScript file that contains the script for executing both Axios POST and GET Method HTTP Requests. Save the file as script.js.

  1. var getBtn = document.getElementById('GetBtn')
  2. var postBtn = document.getElementById('PostBtn')
  3. var responseField = document.getElementById('response-field')
  4.  
  5.  
  6. /**
  7.   * AXIOS GET METHOD
  8.   * @ axios.get(URL,[config])
  9.   */
  10.  
  11. getBtn.addEventListener('click', function(e){
  12. responseField.innerHTML = `HTTP Request using Axios GET Method is on process...`;
  13. axios.get("data.json",{})
  14. .then(response => {
  15. setTimeout(()=>{
  16. // Delaying the Response to Display for 2 seconds
  17. responseField.innerHTML = JSON.stringify(response, null, 3)
  18. }, 2000)
  19. })
  20. .catch(error => {
  21. console.error(error)
  22. responseField.innerHTML = JSON.stringify(error, null, 3)
  23.  
  24. })
  25. })
  26.  
  27. /**
  28.   * AXIOS POST METHOD
  29.   * @ axios.post(URL, data,[config])
  30.   */
  31.  
  32. postBtn.addEventListener('click', function(e) {
  33. responseField.innerHTML = `HTTP Request using Axios POST Method is on process...`;
  34. var formData = new FormData();
  35. formData.append("name", "Mark Cooper")
  36. formData.append("email", "[email protected]")
  37. formData.append("address", "Lot 14 Block 23, 6 St, Here City, Overthere")
  38. axios.post("post-api.php", formData, {
  39. "headers": {"content-type": 'application/x-www-form-urlencoded'},
  40. "responseType":'json'
  41. })
  42. .then(response => {
  43. setTimeout(()=>{
  44. // Delaying the Response to Display for 2 seconds
  45. responseField.innerHTML = JSON.stringify(response, null, 3)
  46. }, 2000)
  47. })
  48. .catch(error => {
  49. console.error(error)
  50. responseField.innerHTML = JSON.stringify(error, null, 3)
  51.  
  52. })
  53.  
  54. })

Snapshot

Here's the snapshot of the sample web application's page interface.

JS Axios POST and GET Method

That's it! I have also provided the complete source code zip file that I created and provided above for this tutorial. You can download it by clicking the Download Button located below this article.

That's the end of this tutorial. I hope this JS HTTP Request using Axios POST and GET Method Tutorial helps you with what you are looking for and that you'll find this useful for your current and future projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding:)

Add new comment