Cookie Consent by Free Privacy Policy Generator ๐Ÿ“Œ Axios GET and POST examples

๐Ÿ  Team IT Security News

TSecurity.de ist eine Online-Plattform, die sich auf die Bereitstellung von Informationen,alle 15 Minuten neuste Nachrichten, Bildungsressourcen und Dienstleistungen rund um das Thema IT-Sicherheit spezialisiert hat.
Ob es sich um aktuelle Nachrichten, Fachartikel, Blogbeitrรคge, Webinare, Tutorials, oder Tipps & Tricks handelt, TSecurity.de bietet seinen Nutzern einen umfassenden รœberblick รผber die wichtigsten Aspekte der IT-Sicherheit in einer sich stรคndig verรคndernden digitalen Welt.

16.12.2023 - TIP: Wer den Cookie Consent Banner akzeptiert, kann z.B. von Englisch nach Deutsch รผbersetzen, erst Englisch auswรคhlen dann wieder Deutsch!

Google Android Playstore Download Button fรผr Team IT Security



๐Ÿ“š Axios GET and POST examples


๐Ÿ’ก Newskategorie: Programmierung
๐Ÿ”— Quelle: dev.to

This article was originally published on the DeadSimpleChat Blog: Axios GET and POST examples

In this article, we are going to learn about how to send get and post requests with Axios. Axios is a promise-based HTTP client for the browser and node.js server.

Axios can run the same code in the browser as well as on the server.

On the NodeJs server side, it uses the ย HTTP module and on the browser side it uses XMLHttpRequests

We are going to learn more about Axios below along with detailed examples of how to send and receive HTTP requests for POST and GET

๐Ÿ’ก
New to DeadSimpleChat? It's a turn key chat that you can easily add to your website or App โ€”without any complicated code. For Virtual / Live events, SaaS App, Social Platform, Education, Gaming, Finance Sign Up for Free

Installing Axios

There are multiple ways to installing axios. here are some

Using npm:

$ npm install axios

using bower

$ bower install axios

Using Yarn:

$ yarn add axios

Using CDN:

JsDelivr and unpkg both provide CDN scirpts for Axios

//using JsDelivr
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
// using unpkg CDN
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Now that we have installed the axios. Let us go towards a easy example on how to send requests

๐Ÿ’ก New to DeadSimpleChat? It's a turn key chat that you can easily add to your website or App โ€”without any complicated code. For Virtual / Live events, SaaS App, Social Platform, Education, Gaming, Finance Sign Up for Free

Making POST Request with Axios with JSON

Now let us create a POST request with Axios and there send the JSON data along with it

first let us require axios in our project like:

const axios = require('axios').default;

// axios.<method> will now provide autocomplete and parameter typings

Now creating a POST request

axios.post('/addCandy',{
    candyName: 'Mars Bar',
    quantity: '24'
});

What are we doing were

We are using the axios.post to make a POST request on the path /addCandy and along with the POST request we are sending the JSON data

{
    candyName: 'Mars Bar',
    quantity: '24'
}

When the server that receives this post request will save this data in its database and send a response back that all is ok with a response code of 200 or it will send a response that some error has occurred along with corresponding response code and error message

We need to record what message and code the server has sent we will be doing that next

axios.post('/addCandy',{
    candyName: 'Mars Bar',
    quantity: '24'
}).then(function(response){
    console.log(response)
})

Also, it might happen that we are making a mistake in making the request and an error is happening on our side.

We need to catch that error as well. Let's add another line of code to catch that error as well

 .catch(function (error) {
    console.log(error);
  });

the complete code looks like

axios.post('/addCandy',{
    candyName: 'Mars Bar',
    quantity: '24'
}).then(function(response){
    console.log(response)
})
.catch(function (error) {
    console.log(error);
  });

The POST Request can also be sent by passing the relevant config to the axios

axios(config);
//sending a post request
axios({
  method: 'post',
  url: '/addCandy',
  data: {
    candyName: 'Mars Bar',
    quantity: '24'
  }
});

There are also alias methods that can be used as an alternative to the above methods

axios.post(url,[data[,config]])

Making POST Request with Axios using Async/Await

A cleaner and simpler way of making POST request with Axios is by using the async await keywords

POST request with HTTP headers

Adding HTTP headers to our post Request is quite easy. Just add the headers to the config

//sending a post request
axios({
  method: 'post',
  url: '/addCandy',
  data: {
    candyName: 'Mars Bar',
    quantity: '24'
  },
  headers: {'X-Custom-Header': 'foobar'}
}).then(function(response){
    console.log(response)
});

Error Handling with POST and Get Request

It is quite easy to handle error requests with Axios. Here is an example of how you can handle error requests with Axios

//sending a post request
axios({
    method: 'post',
    url: '/addCandy',
    data: {
      candyName: 'Mars Bar',
      quantity: '24'
    }
  }).catch(function (error) {
    if(error.response){
        // the request was made and the server responded with the response code that is out of 2xx
        console.log(error.response.data);
        console.log(error.response.status);
        console.log(error.response.headers);
    } else if (error.request) {
        // the request was made but no response was recieved the `error.request` is an instance of XMLHttpRequest in the browser and a instance of http.ClientRequet in Node.Js
        console.log(error.request);
    }else {
        // Something happened that triggered an error
        console.log('error', error.message);
    }
    console.log('err',error.config);
  });

What are we doing here

We are sending a POST request using Axios and catching the error of it occurs

If the error has response code out of the 2xx success code then we are logging the data, response code and the http headers that are returned by the server to better understand why the error occurred

If there is some problem with the request that we are sending then we are logging that to the console

If there is no problem with the request or the response and there is some other error that is occurring than we are also logging that to the console

In the end if there is something wrong with the config then we are logging that to the console

ValidateStatus config option

Using the validateStatus config option, we can define the HTTP codes that should throw an error. like for example

axios.get('/get-candies', {
  validateStatus: function (status) {
    return status < 500; // Resolve only if the status code is less than 500
  }
})

Using toJSON

If you need more information about the HTTP error code you can convert the error code to JSON using the toJSON function.

That would give you more information regarding the error.

axios.get('/get-candies')
  .catch(function (error) {
    console.log(error.toJSON());
  });

Making GET Request with Axios with JSON

First let us add the Axios to our project

const axios = require('axios').default;

and let us make the GET request

// Make a request for candies
axios.get('/get-candies')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

We are making a GET request to the url '/get-candies' to get a list of candies from the server. Then we are logging the response that we get from the server on to the console.

The server might give us the data in the form of a list of candies along with the 2xx response code or the server might give us an error

If the server gives us an error we are logging that error on to the console

Now, we might want to add params to our request like for example

// Make a request forcandies from a brand name
axios.get('/get-candies?brand="mars"')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

Now, we have added a params like ?parameterName=value

We can also make the GET request using the alternative method

axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // always executed
  });  

This method is the similar to the previous method only thing being we have changed the config a bit for readability and it is easier this way to pass multiple parameters while sending the requests

Making GET Request with Axios using Async/Await

It is also very easy to make requests using async / await keywords. Keep in mind though older browsers like IE do not support the async keyword.

var candies = async function getCandies() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

This way we can send GET requests using the Async / Await keywords

๐Ÿ’ก
New to DeadSimpleChat? It's a turn key chat that you can easily add to your website or App โ€”without any complicated code. For Virtual / Live events, SaaS App, Social Platform, Education, Gaming, Finance Sign Up for Free

Intercepting req and res

You can intercept requests or response befoer they are handled by then or catch

Create a intereceptor like

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

and if you need to add a response interceptor then

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });

If you need to remove the interceptor later on in the code

const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

Response Schema

The response schema of a request is as follows. You can use the response schema to log information that is relevant to you

{
  // Response provided by the server is data
  data: {},

  // HTTP code sent by the server is status
  status: 200,

  // `headers` the HTTP headers that the server responded with
  // All header names are lower cased and can be accessed using the bracket notation.
  // Example: `response.headers['content-type']`
  headers: {},

  // `config` is the config that was provided to `axios` for the request
  config: {},

  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance in the browser
  request: {}
}

You can log the information that is relevant to you like

axios.get('/candies')
  .then(function (response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  });

How to cancel requests

You can cancel Axios requests using the AbortController

const controller = new AbortController();

axios.get('/candies', {
   signal: controller.signal
}).then(function(response) {
   //...
});
// cancel the request
controller.abort()

A note the cancelToken API has been depricated since the version v0.22.0 and no longer works in the newer versions

URL encoding instead of JSON

By default the Axios serializes the body object in JSON but if you wish to send the request in application/x-www-form-urlencoded then you can do so using the below options

In the Browser

const params = new URLSearchParams()

params.append('param1', 'value1');
params.append('param2', 'value2');

axios.post('/send-candy',params);

Note the URLSearchParams is not supported by all browsers

In Node.JS

using the querystring module you can send the requests for example

const querystring = require('querystring');
axios.post('https://candies.com/', querystring.stringify({ candy: 'mars bar' }));

Conclusion

In this article I explained with examples how to send POST and GET requests with Axios

...



๐Ÿ“Œ Axios GET and POST examples


๐Ÿ“ˆ 51.88 Punkte

๐Ÿ“Œ Axios Italia Axios RE 1.7.0/7.0.0 RELogOff.aspx Error_Parameters cross site scripting


๐Ÿ“ˆ 48.09 Punkte

๐Ÿ“Œ Axios Italia Axios RE 1.7.0/7.0.0 Connection REDefault.aspx DBIDX privilege escalation


๐Ÿ“ˆ 48.09 Punkte

๐Ÿ“Œ Axios Italia Axios RE 1.7.0/7.0.0 Error Message ASP.NET information disclosure


๐Ÿ“ˆ 48.09 Punkte

๐Ÿ“Œ 'Facebook, Axios And NBC Paid This Guy To Whitewash Wikipedia Pages'


๐Ÿ“ˆ 25.95 Punkte

๐Ÿ“Œ How to use Axios interceptors to handle 401 API errors and refresh tokens in typescript.


๐Ÿ“ˆ 25.95 Punkte

๐Ÿ“Œ A Beginner's Guide to Using Fetch and Axios to Consume REST APIs inย React


๐Ÿ“ˆ 25.95 Punkte

๐Ÿ“Œ Creating Axios Interceptor in React and NextJs


๐Ÿ“ˆ 25.95 Punkte

๐Ÿ“Œ Python Program Examples โ€“ Simple Code Examples for Beginners


๐Ÿ“ˆ 25.54 Punkte

๐Ÿ“Œ Man pages with examples. Looking for a website with lot of examples for Linux commands. (Not for beginners). - sed, awk, find, ls ...


๐Ÿ“ˆ 25.54 Punkte

๐Ÿ“Œ Axios Systems enthรผllt auf SITS19 die neuste Weiterentwicklung von assyst ITOM


๐Ÿ“ˆ 24.05 Punkte

๐Ÿ“Œ A Denial of Service vulnerability discovered in the Axios JavaScript package - affecting all versions of the popular HTTP client


๐Ÿ“ˆ 24.05 Punkte

๐Ÿ“Œ A Denial of Service vulnerability discovered in the Axios JavaScript package - affecting all versions of the popular HTTP client


๐Ÿ“ˆ 24.05 Punkte

๐Ÿ“Œ Axios Italia Axioscloud Sissiweb Registro Elettronico 1.7.0 secret/relogoff.aspx Error_Desc cross site scripting


๐Ÿ“ˆ 24.05 Punkte

๐Ÿ“Œ Axios up to 0.18.0 Content maxContentLength Crash denial of service


๐Ÿ“ˆ 24.05 Punkte

๐Ÿ“Œ How to mock Axios HTTP calls with Jest


๐Ÿ“ˆ 24.05 Punkte

๐Ÿ“Œ Axios Package 0.21.0 on npm Redirect server-side request forgery


๐Ÿ“ˆ 24.05 Punkte

๐Ÿ“Œ Vue-Kommunikation รผber Fetch und Axios - Dev-Insider


๐Ÿ“ˆ 24.05 Punkte

๐Ÿ“Œ Handle Axios Error in Typescript


๐Ÿ“ˆ 24.05 Punkte

๐Ÿ“Œ Adeus, Axios! Descubra como esse novo cรณdigo pode substituir completamente a biblioteca de requisiรงรตes HTTP mais popular.


๐Ÿ“ˆ 24.05 Punkte

๐Ÿ“Œ You Don't Need Axios


๐Ÿ“ˆ 24.05 Punkte

๐Ÿ“Œ Setting Headers with Axios in Node JS


๐Ÿ“ˆ 24.05 Punkte

๐Ÿ“Œ How to mock Axios HTTP calls with Jest


๐Ÿ“ˆ 24.05 Punkte

๐Ÿ“Œ Why using AXIOS with Typescript?


๐Ÿ“ˆ 24.05 Punkte

๐Ÿ“Œ Use axios as better practice in ReactJS


๐Ÿ“ˆ 24.05 Punkte

๐Ÿ“Œ Post-Truth, Post-West, Post-Order: Der Hack der Weltordnung


๐Ÿ“ˆ 22.6 Punkte

๐Ÿ“Œ Deutsche Post DHL Group: App โ€žPost & DHLโ€œ fasst die wichtigsten Post- und Paket-Services zusammen


๐Ÿ“ˆ 22.6 Punkte

๐Ÿ“Œ E-POST Portal, E-POST Cloud und E-POST App werden eingestellt


๐Ÿ“ˆ 22.6 Punkte

๐Ÿ“Œ The differences between Hard and Soft Links in Linux explained with illustrated examples [Medium blog post]


๐Ÿ“ˆ 22.21 Punkte

๐Ÿ“Œ Can Macs Get Ransomware? Examples + Prevention Strategies | UpGuard


๐Ÿ“ˆ 18.39 Punkte

๐Ÿ“Œ Facebook and Twitterโ€™s Handling of New York Post Hunter Biden Story Bodes Poorly for Post-Election Period


๐Ÿ“ˆ 16.97 Punkte

๐Ÿ“Œ Microsoft: You get ads! You get ads! You get ads!


๐Ÿ“ˆ 16.88 Punkte

๐Ÿ“Œ HTML and Javascript Teacher - Code examples in HTML and Javascript.


๐Ÿ“ˆ 16.59 Punkte

๐Ÿ“Œ You get a lawsuit! And you get a lawsuit! And you! Now Apple sued over CPU security flaws


๐Ÿ“ˆ 15.07 Punkte











matomo