How to use Axios with different data formats? (2024)

APIs are frequently used in modern web applications to exchange data between the front-end and back-end.

Axios, a popular JavaScript library for making HTTP requests, provides a straightforward and adaptable way to interact with RESTful endpoints.

However, depending on the data type you're working with, you may need to modify your Axios usage to accommodate different formats like JSON or XML.

Using Axios with JSON data format

JSON data has grown to be the most preferred data format for APIs due to its simplicity. In this section, we'll look at how to send and receive HTTP requests using Axios and JSON data, as well as how to handle response data in JavaScript.

Sending a GET request with Axios and JSON data

To send a GET request with Axios and JSON data, use the axios.get() method and pass in the URL of the API endpoint from where you want to retrieve data. Let’s look at an example by using the Famous Quotes API from Rapid API Hub.

Loading component...

Once you are signed in, make sure you subscribe to the API.

js

const axios = require("axios");

const options = {

params: { category: 'all', count: '2' },

headers: {

'X-RapidAPI-Key': 'your-api-key',

'X-RapidAPI-Host': 'famous-quotes4.p.rapidapi.com'

}

};

axios.get('https://famous-quotes4.p.rapidapi.com/random', options)

.then(function (response) {

console.log(response.data);

})

.catch(function (error) {

console.error(error);

});

Sending a POST request with Axios and JSON data

To send a POST request with Axios and JSON data, you can use the axios.post() method and pass in the URL of the API endpoint you want to send data to, as well as the JSON data you want to send. For example:

js

const data = {

name: 'John Doe',

email: '[email protected]'

};

axios.post('https://example.com/api/data', data)

.then(response => {

// Handle successful response

console.log(response.data);

})

.catch(error => {

// Handle error

console.error(error);

});

Using Axios with XML data format

Let’s see how we can use Axios with XML data format, including sending GET and POST requests.

Sending a GET request with Axios and XML data

To send a GET request with Axios and XML data, we can use the axios.get method with the responseType option set to document.

We will use the Routing Number Bank Lookup API from Rapid API Hub in this example.

js

const axios = require("axios");

axios

.get("https://routing-number-bank-lookup.p.rapidapi.com/api/v1/121000248", {

params: { format: "xml", paymentType: "ach" },

headers: {

"X-RapidAPI-Key": "your-api-key",

"X-RapidAPI-Host": "routing-number-bank-lookup.p.rapidapi.com",

},

responseType: "document",

})

.then(function (response) {

console.log(response.data);

})

.catch(function (error) {

console.error(error);

});

Sending a POST request with Axios and XML data

To send a POST request with Axios and XML data, we can use the axios.post method with the request body containing the XML data. Here's an example:

js

const axios = require("axios");

const xmlData = `

<root>

<name>John</name>

<age>30</age>

</root>

`;

axios.post("http://example.com/api/data.xml", xmlData, {

headers: {

"Content-Type": "text/xml",

},

}).then((response) => {

console.log(response.data);

}).catch((error) => {

console.error(error);

});

Wrap up

Axios is a powerful JavaScript library that provides an easy-to-use API for making HTTP requests. One of its most useful features is the ability to handle different data formats, including JSON and XML.

When making requests with Axios, it is important to specify the correct data format in the request headers and to set the responseType option to match the expected data format of the response.

How to use Axios with different data formats? (2024)
Top Articles
CA/Changing Trust Settings - MozillaWiki
Goals for Estate Planning | Stein Sperling
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Selly Medaline
Latest Posts
Article information

Author: Sen. Ignacio Ratke

Last Updated:

Views: 5489

Rating: 4.6 / 5 (56 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Sen. Ignacio Ratke

Birthday: 1999-05-27

Address: Apt. 171 8116 Bailey Via, Roberthaven, GA 58289

Phone: +2585395768220

Job: Lead Liaison

Hobby: Lockpicking, LARPing, Lego building, Lapidary, Macrame, Book restoration, Bodybuilding

Introduction: My name is Sen. Ignacio Ratke, I am a adventurous, zealous, outstanding, agreeable, precious, excited, gifted person who loves writing and wants to share my knowledge and understanding with you.