• We just launched and are currently in beta. Join us as we build and grow the community.

JS HTTP Request using Axios POST and GET Method Tutorial

jack554

Grey Hat
J Rep
0
0
0
Rep
0
J Vouches
0
0
0
Vouches
0
Posts
70
Likes
105
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 300 XP
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. $ npm install axios

  5. /**
  6. * Using Yarn
  7. */

  8. $ yarn add axios

  9. /**
  10. * Using Bower
  11. */

  12. $ bower install axios

Using CDN

  1. <!-- Using JSDelivr CDN -->
  2. <script

    src

    =

    "https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"

    ></

    script

    >

  3. <!-- Using unpkg CDN -->
  4. <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. axios(

    {
  5. method:

    'post'

    ,
  6. url:

    'yourapiurlhere.php'

    ,
  7. headers:

    {
  8. 'Content-Type'

    :

    'application/x-www-form-urlencode'
  9. }

    ,
  10. data:

    {
  11. 'name'

    :

    'Claire Blake'

    ,
  12. 'email'

    :

    '[email protected]'
  13. }
  14. }

    )

    .then

    (

    response =>

    {
  15. //Request's Response
  16. console.log

    (

    response)
  17. }

    )

    .catch

    (

    error =>

    {
  18. // Catch Request's Error
  19. console.error

    (

    error)
  20. }

    )

  21. /**
  22. * Axios Post Method : Syntax Example 2
  23. */
  24. var

    data =

    new

    FormData(

    )

    ;
  25. data.append

    (

    'name'

    ,

    'Claire Blake'

    )
  26. data.append

    (

    'email'

    ,

    '[email protected]'

    )

  27. axios.post

    (

    'yourapiurlhere.php'

    ,

    {
  28. headers:

    {
  29. 'content-type'

    :

    'application/x-www-form-urlencode'
  30. }
  31. }

    )

    .then

    (

    response =>

    {
  32. //Request's Response
  33. console.log

    (

    response)
  34. }

    )

    .catch

    (

    error =>

    {
  35. // Catch Request's Error
  36. console.error

    (

    error)
  37. }

    )

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. axios(

    {
  5. method:

    'get'

    ,
  6. url:

    'test.json'

    ,
  7. responseType:

    'json'
  8. }

    )

    .then

    (

    response =>

    {
  9. //Request's Response
  10. console.log

    (

    response)
  11. }

    )

    .catch

    (

    error =>

    {
  12. // Catch Request's Error
  13. console.error

    (

    error)
  14. }

    )


  15. /**
  16. * Axios Post Method : Syntax Example 2
  17. */

  18. axios.post

    (

    'test.json'

    ,

    {
  19. responseType:

    'json'
  20. }

    )

    .then

    (

    response =>

    {
  21. //Request's Response
  22. console.log

    (

    response)
  23. }

    )

    .catch

    (

    error =>

    {
  24. // Catch Request's Error
  25. console.error

    (

    error)
  26. }

    )

  27. /**
  28. * Axios Post Method : Syntax Example 3
  29. */

  30. axios(

    'data.json'

    )

    .then

    (

    response =>

    {
  31. //Request's Response
  32. console.log

    (

    response)
  33. }

    )

    .catch

    (

    error =>

    {
  34. // Catch Request's Error
  35. console.error

    (

    error)
  36. }

    )


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. <head

    >
  4. <meta

    charset

    =

    "UTF-8"

    >
  5. <meta

    http-equiv

    =

    "X-UA-Compatible"

    content

    =

    "IE=edge"

    >
  6. <meta

    name

    =

    "viewport"

    content

    =

    "width=device-width, initial-scale=1.0"

    >
  7. <title

    >

    JS HTTP Request using Axios</

    title

    >
  8. <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"

    /

    >
  9. <link

    rel

    =

    "stylesheet"

    href

    =

    "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"

    integrity=

    "sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi"

    crossorigin=

    "anonymous"

    >
  10. <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

    >
  11. <script

    src

    =

    "https://code.jquery.com/jquery-3.6.1.js"

    integrity=

    "sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI="

    crossorigin=

    "anonymous"

    ></

    script

    >
  12. <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

    >
  13. <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

    >
  14. <style

    >
  15. html, body{
  16. min-height:100%;
  17. width:100%;
  18. }
  19. tbody:empty:after{
  20. content:'No records found'
  21. }
  22. </

    style

    >
  23. </

    head

    >
  24. <body

    >
  25. <nav class

    =

    "navbar navbar-expand-lg navbar-dark bg-primary bg-gradient"

    >
  26. <div

    class

    =

    "container"

    >
  27. <a

    class

    =

    "navbar-brand"

    href

    =

    "./"

    >

    JS HTTP Request using Axios</

    a

    >

  28. <div

    >
  29. <a

    href

    =

    "https://sourcecodester.com"

    class

    =

    "text-light fw-bolder h6 text-decoration-none"

    target

    =

    "_blank"

    >

    SourceCodester</

    a

    >
  30. </

    div

    >
  31. </

    div

    >
  32. </

    nav>
  33. <div

    class

    =

    "container-fluid px-5 my-3"

    >
  34. <div

    class

    =

    "col-lg-5 col-md-7 col-sm-12 mx-auto"

    >
  35. <h3

    class

    =

    "text-center"

    ><b

    >

    Axios POST and GET Method</

    b

    ></

    h3

    >
  36. <div

    class

    =

    "d-flex w-100 justify-content-center"

    >
  37. <hr

    class

    =

    "w-50"

    >
  38. </

    div

    >
  39. <div

    class

    =

    "card rounded-0 shadow mb-3"

    >
  40. <div

    class

    =

    "card-body"

    >
  41. <div

    class

    =

    "container-fluid"

    >
  42. <div

    class

    =

    "mb-3"

    >
  43. <div

    class

    =

    "d-flex justify-content-center"

    >
  44. <button

    class

    =

    "btn btn-primary rounded-pill col-lg-3 col-md-5 col-sm-12 me-2"

    id

    =

    "GetBtn"

    >

    Get</

    button

    >
  45. <button

    class

    =

    "btn btn-info rounded-pill col-lg-3 col-md-5 col-sm-12 me-2"

    id

    =

    "PostBtn"

    >

    Post</

    button

    >
  46. </

    div

    >
  47. </

    div

    >
  48. <hr

    >
  49. <label

    for

    =

    ""

    class

    =

    "form-label"

    >

    Response</

    label

    >
  50. <pre

    id

    =

    "response-field"

    class

    =

    "bg-dark p-3 text-light"

    >

  51. </

    pre

    >
  52. </

    div

    >
  53. </

    div

    >
  54. </

    div

    >
  55. </

    div

    >
  56. </

    div

    >
  57. </

    body

    >
  58. <script

    src

    =

    "./script.js"

    ></

    script

    >
  59. </

    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"

    :

    "[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. if

    (

    $_SERVER

    [

    'REQUEST_METHOD'

    ]

    ==

    "POST"

    )

    {
  3. echo

    json_encode

    (

    $_POST

    )

    ;
  4. }

    else

    {
  5. echo

    json_encode

    (

    [

    'error'

    =>

    'Request is not a POST Method'

    ]

    )

    ;
  6. }

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. * AXIOS GET METHOD
  6. * @ axios.get(URL,[config])
  7. */

  8. getBtn.addEventListener

    (

    'click'

    ,

    function

    (

    e)

    {
  9. responseField.innerHTML

    =

    `HTTP Request using Axios GET Method is on process...`;
  10. axios.get

    (

    "data.json"

    ,

    {

    }

    )
  11. .then

    (

    response =>

    {
  12. setTimeout(

    (

    )

    =>

    {
  13. // Delaying the Response to Display for 2 seconds
  14. responseField.innerHTML

    =

    JSON.stringify

    (

    response,

    null

    ,

    3

    )
  15. }

    ,

    2000

    )
  16. }

    )
  17. .catch

    (

    error =>

    {
  18. console.error

    (

    error)
  19. responseField.innerHTML

    =

    JSON.stringify

    (

    error,

    null

    ,

    3

    )

  20. }

    )
  21. }

    )

  22. /**
  23. * AXIOS POST METHOD
  24. * @ axios.post(URL, data,[config])
  25. */

  26. postBtn.addEventListener

    (

    'click'

    ,

    function

    (

    e)

    {
  27. responseField.innerHTML

    =

    `HTTP Request using Axios POST Method is on process...`;
  28. var

    formData =

    new

    FormData(

    )

    ;
  29. formData.append

    (

    "name"

    ,

    "Mark Cooper"

    )
  30. formData.append

    (

    "email"

    ,

    "[email protected]"

    )
  31. formData.append

    (

    "address"

    ,

    "Lot 14 Block 23, 6 St, Here City, Overthere"

    )
  32. axios.post

    (

    "post-api.php"

    ,

    formData,

    {
  33. "headers"

    :

    {

    "content-type"

    :

    'application/x-www-form-urlencoded'

    }

    ,
  34. "responseType"

    :

    'json'
  35. }

    )
  36. .then

    (

    response =>

    {
  37. setTimeout(

    (

    )

    =>

    {
  38. // Delaying the Response to Display for 2 seconds
  39. responseField.innerHTML

    =

    JSON.stringify

    (

    response,

    null

    ,

    3

    )
  40. }

    ,

    2000

    )
  41. }

    )
  42. .catch

    (

    error =>

    {
  43. console.error

    (

    error)
  44. responseField.innerHTML

    =

    JSON.stringify

    (

    error,

    null

    ,

    3

    )

  45. }

    )

  46. }

    )

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:)


Download
You must upgrade your account or reply in the thread to view hidden text.
 

449,193

322,229

322,238

Top