Parse XML Responses to JSON with Axios
By default, Axios automatically serializes JSON responses into
JavaScript objects, but it treats XML payloads as plain text strings.
This guide demonstrates how to configure Axios to automatically parse
custom XML responses into JSON objects using the
transformResponse hook and an XML parsing library like
fast-xml-parser.
1. Install Required Dependencies
Axios does not include a built-in XML parser. You need to install an
XML-to-JSON library. fast-xml-parser is widely recommended
due to its performance and zero dependencies:
npm install axios fast-xml-parser2. Configure
transformResponse in a Single Request
You can use the transformResponse array inside your
Axios request configuration. This property allows you to intercept and
modify the response data before it reaches your .then() or
await handlers.
import axios from 'axios';
import { XMLParser } from 'fast-xml-parser';
const parser = new XMLParser({
ignoreAttributes: false,
attributeNamePrefix: "@_"
});
async function fetchXmlData() {
try {
const response = await axios.get('https://example.com/api/data.xml', {
responseType: 'text', // Ensure the response is handled as text
transformResponse: [
(data) => {
// Parse string to JSON if valid data exists
if (data && typeof data === 'string') {
return parser.parse(data);
}
return data;
}
]
});
console.log(response.data); // Outputs parsed JSON object
} catch (error) {
console.error('Request failed:', error);
}
}3. Create a Reusable Axios Instance
If you are communicating with an API that consistently returns XML, create a dedicated Axios instance rather than configuring each request individually:
import axios from 'axios';
import { XMLParser } from 'fast-xml-parser';
const parser = new XMLParser();
const xmlApiClient = axios.create({
baseURL: 'https://api.example.com',
headers: {
'Accept': 'application/xml, text/xml'
},
responseType: 'text',
transformResponse: [
(data) => {
try {
return parser.parse(data);
} catch (err) {
return data; // Fallback to raw string if parsing fails
}
}
]
});
// Usage
export async function getResource(endpoint) {
const response = await xmlApiClient.get(endpoint);
return response.data; // Automatically parsed JSON
}4. Key Configuration Options
responseType: 'text': Explicitly telling Axios to expect text prevents unexpected pre-processing when the server responds with content types likeapplication/xmlortext/xml.- Error Handling: Wrapping the parser function inside
a
try...catchblock insidetransformResponseensures that invalid XML responses do not cause unhandled runtime exceptions during data transformation.