I have a react application in which I want the user to be able to upload code files that he can then view.
So naturally, .json files are also accepted. Now to get the file contents, I use axios to make a get request to the file on the server.
This works fine for everything except JSON files, which are automatically parsed and therefore not available as a String, but as a javascript object. Turning them into a string again with JSON.stringify
removes all line breaks, so I can't do that.
Is there any way to stop Axios from automatically parsing JSON?
Axios parses the response based on the HTTP response's Content-Type header. When the response's content type is application/json , Axios will automatically try to parse the response into a JavaScript object. Keep in mind that the response headers are sent by the server.
By default, axios serializes JavaScript objects to JSON.
To post request with JSON data with Axios, we call axios. post with the JSON payload as the 2nd argument. const dt = { data: { value: "abc" } }; const request = axios. post(url, dt);
LuleBes answer didnt work for me. What did work was:
transformResponse: (res) => { return res; },
As in:
axios.get(url, {
headers,
transformResponse: (res) => {
// Do your own parsing here if needed ie JSON.parse(res);
return res;
},
responseType: 'json'
}).then(response => {
// response.data is an unparsed string
});
Ok I figured out how that would work. You can disable response processing by just passing the transformResponse
Array in the config, which is then used instead of the the default. There you just provide an empty array or an array of functions you need to apply to your response, like this:
axios.get(URL, {transformResponse: []})
.then(response => {/*response.data is plain text*/});
Set the following option to force axios not to parse the response:
transformResponse: x => x
Usage:
let response = await axios.get('/static/data.json', {
transformResponse: x => x
});
Now response.data
is a string
as previously it was an object
For my case of Server Side Rendering (SSR) need to explicitly setup
responseType
parameter which is, according to axios documentation, 'json' by default
return axios.get(url, {
transformResponse: res => res,
responseType: 'text'
})
Without this 'responseType' parameter I was confused when the marked solution worked in tests and failed in the browser.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With