How to Get Plain Text Responses with Axios
By default, the Axios HTTP client automatically attempts to parse
response data as JSON. However, you can configure Axios to process and
return responses as plain text by setting the responseType
option to 'text'. This guide covers how to set this
property on individual requests, within custom Axios instances, and
globally, as well as how to bypass standard response transformations to
ensure raw text output.
Using the
responseType Property
To receive a response as plain text, set the
responseType configuration option to
'text'.
Example: Per-Request Configuration
Pass the configuration object as the second argument in a
GET request or as the third argument in a POST
request:
const axios = require('axios');
axios.get('https://example.com/api/data', {
responseType: 'text'
})
.then(response => {
console.log(typeof response.data); // "string"
console.log(response.data);
})
.catch(error => {
console.error('Error fetching data:', error);
});For a POST request:
axios.post('https://example.com/api/submit',
{ key: 'value' },
{ responseType: 'text' }
)
.then(response => {
console.log(response.data);
});Configuring an Axios Instance
If you are working with an API that consistently returns plain text
(such as CSV, logs, or raw HTML), you can set
responseType: 'text' globally for a reusable instance using
axios.create():
const textClient = axios.create({
baseURL: 'https://example.com/api',
responseType: 'text'
});
// All requests using textClient will return string payloads
textClient.get('/log-file')
.then(response => {
console.log(response.data);
});Overriding Response Transformers
In standard setups, setting responseType: 'text' is
sufficient. However, if Axios or an interceptor is still applying
transformations, you can explicitly override the
transformResponse array with a passthrough function to
prevent any parsing:
axios.get('https://example.com/api/data', {
responseType: 'text',
transformResponse: [(data) => data] // Returns the raw payload without modification
})
.then(response => {
console.log(response.data);
});Global Configuration
To enforce plain text responses across all default axios
calls throughout your application, modify the global defaults:
axios.defaults.responseType = 'text';