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
- /**
- * Using NPM
- */
- $ npm install axios
- /**
- * Using Yarn
- */
- $ yarn add axios
- /**
- * Using Bower
- */
- $ bower install axios
Using CDN
Axios POST Method syntax
The below snippets demonstrate the syntax of how to implement or execute the Axios Post Method.
- /**
- * Axios Post Method : Syntax Example 1
- */
- axios({
- method: 'post',
- url: 'yourapiurlhere.php',
- headers:{
- 'Content-Type' : 'application/x-www-form-urlencode'
- },
- data:{
- 'name': 'Claire Blake',
- }
- }).then( response =>{
- //Request's Response
- console.log(response)
- } ).catch( error =>{
- // Catch Request's Error
- console.error(error)
- } )
- /**
- * Axios Post Method : Syntax Example 2
- */
- var data = new FormData();
- data.append('name', 'Claire Blake')
- axios.post('yourapiurlhere.php', {
- headers:{
- 'content-type' : 'application/x-www-form-urlencode'
- }
- }).then( response =>{
- //Request's Response
- console.log(response)
- } ).catch( error =>{
- // Catch Request's Error
- console.error(error)
- } )
Axios GET Method syntax
The below snippets demonstrate the syntax of how to implement or execute the Axios GET Method.
- /**
- * Axios Post Method : Syntax Example 1
- */
- axios({
- method: 'get',
- url: 'test.json',
- responseType:'json'
- }).then( response =>{
- //Request's Response
- console.log(response)
- } ).catch( error =>{
- // Catch Request's Error
- console.error(error)
- } )
- /**
- * Axios Post Method : Syntax Example 2
- */
- axios.post('test.json', {
- responseType:'json'
- }).then( response =>{
- //Request's Response
- console.log(response)
- } ).catch( error =>{
- // Catch Request's Error
- console.error(error)
- } )
- /**
- * Axios Post Method : Syntax Example 3
- */
- axios('data.json').then( response =>{
- //Request's Response
- console.log(response)
- } ).catch( error =>{
- // Catch Request's Error
- console.error(error)
- } )
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.
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <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" />
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
- <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>
- <style>
- html, body{
- min-height:100%;
- width:100%;
- }
- tbody:empty:after{
- content:'No records found'
- }
- </style>
- </head>
- <body>
- <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
- <div class="container">
- <div>
- </div>
- </div>
- </nav>
- <div class="container-fluid px-5 my-3" >
- <div class="col-lg-5 col-md-7 col-sm-12 mx-auto">
- <div class="d-flex w-100 justify-content-center">
- <hr class="w-50">
- </div>
- <div class="card rounded-0 shadow mb-3">
- <div class="card-body">
- <div class="container-fluid">
- <div class="mb-3">
- <div class="d-flex justify-content-center">
- </div>
- </div>
- <hr>
- <pre id="response-field" class="bg-dark p-3 text-light">
- </pre>
- </div>
- </div>
- </div>
- </div>
- </div>
- </body>
- </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
- [
- {
- "name": "Ella Daniel",
- "phone": "(567) 380-9992"
- },
- {
- "name": "Melyssa Cantrell",
- "phone": "1-526-413-2563"
- },
- {
- "name": "Chaim Buchanan",
- "phone": "1-316-685-9786"
- },
- {
- "name": "Desiree Welch",
- "phone": "(591) 884-4171"
- },
- {
- "name": "Hu Ward",
- "phone": "(858) 403-3635"
- }
- ]
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.
- <?php
- if($_SERVER['REQUEST_METHOD'] == "POST"){
- }else{
- }
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.
- var getBtn = document.getElementById('GetBtn')
- var postBtn = document.getElementById('PostBtn')
- var responseField = document.getElementById('response-field')
- /**
- * AXIOS GET METHOD
- * @ axios.get(URL,[config])
- */
- getBtn.addEventListener('click', function(e){
- responseField.innerHTML = `HTTP Request using Axios GET Method is on process...`;
- axios.get("data.json",{})
- .then(response => {
- setTimeout(()=>{
- // Delaying the Response to Display for 2 seconds
- responseField.innerHTML = JSON.stringify(response, null, 3)
- }, 2000)
- })
- .catch(error => {
- console.error(error)
- responseField.innerHTML = JSON.stringify(error, null, 3)
- })
- })
- /**
- * AXIOS POST METHOD
- * @ axios.post(URL, data,[config])
- */
- postBtn.addEventListener('click', function(e) {
- responseField.innerHTML = `HTTP Request using Axios POST Method is on process...`;
- var formData = new FormData();
- formData.append("name", "Mark Cooper")
- formData.append("address", "Lot 14 Block 23, 6 St, Here City, Overthere")
- axios.post("post-api.php", formData, {
- "headers": {"content-type": 'application/x-www-form-urlencoded'},
- "responseType":'json'
- })
- .then(response => {
- setTimeout(()=>{
- // Delaying the Response to Display for 2 seconds
- responseField.innerHTML = JSON.stringify(response, null, 3)
- }, 2000)
- })
- .catch(error => {
- console.error(error)
- responseField.innerHTML = JSON.stringify(error, null, 3)
- })
- })
Snapshot
Here's the snapshot of the sample web application's page interface.
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
- 574 views