I think there is some confusion about the term "JSON"
I think what you mean is that you want the result from Axios to be a Javascript object, not a JSON string. The confusion is common because we often call Javascript objects "JSON objects" as a slang term.
If you type the following into the console, the resulting value of a
will be a Javascript object:
const a = { x: 10}
Some people would call a
a JSON object, but strictly speaking it is not. The JSON representation of a
is the following string:
{ "x": 10 }
What Axios returns to you_ not a JSON string, but a Javascript object
This contains various pieces of information, in different properties of the object. Important to us here are:
The "data" property, which may be a string containing HTML, or a Javascript object, or something else.
Within the "headers" property, the "content-type" subproperty. This will begin with "application/json" if data
is a Javascript object, and "text/html" if data
is an HTML response.
Here is your code showing the content-type of the server response explicitly.
axios.get('http://cataas.com/cat?html=true')
.then(response => {
console.log("Example of an API returning an HTML response")
const contentType = response.headers["content-type"];
const data = response.data;
console.log("Type of response data is:", contentType)
console.log("Because it is a long string, I am just going to show a few characters of it:", data.slice(0, 40))
})
.catch((err) => console.log(`Error: ${err}`))
axios.get('https://dummyjson.com/products/1')
.then(response => {
console.log("Example of an API returning an JSON response")
const contentType = response.headers["content-type"];
const data = response.data;
console.log("Type of response data is:", contentType)
console.log("Because it is a small object, I am going to show it all:", data)
})
.catch((err) => console.log(`Error: ${err}`))
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.3.4/axios.min.js" integrity="sha512-LUKzDoJKOLqnxGWWIBM4lzRBlxcva2ZTztO8bTcWPmDSpkErWx0bSP4pdsjNH8kiHAUPaT06UXcb+vOEZH+HpQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
The http://cataas.com/cat?html=true
API returns an HTML string
Axios faithfully gives you that string in the data
property.
<!DOCTYPE html>
<html lang="en">
<header>
<meta charset="utf-8">
</header>
<body>
<img alt="ltBmKwnyGcagdHo3" src="/cat/ltBmKwnyGcagdHo3">
</body>
</html>
The https://dummyjson.com/products/1
API returns a JSON string to Axios
Axios automatically converts that JSON string into a Javascript object for you.
{"id":1,"title":"iPhone 9","description":"An apple mobile which is nothing like apple","price":549,"discountPercentage":12.96,"rating":4.69,"stock":94,"brand":"Apple","category":"smartphones","thumbnail":"https://i.dummyjson.com/data/products/1/thumbnail.jpg","images":["https://i.dummyjson.com/data/products/1/1.jpg","https://i.dummyjson.com/data/products/1/2.jpg","https://i.dummyjson.com/data/products/1/3.jpg","https://i.dummyjson.com/data/products/1/4.jpg","https://i.dummyjson.com/data/products/1/thumbnail.jpg"]}
One way to achieve what you want:
Read response.headers["content-type"]
If it begins with application/json
, then you are in luck: just treat response.data
as a Javascript object
If it begins with text/html
, despite you having requested a JSON, then something has gone wrong. You could read response.data
as HTML, and look for whether the server said anything helpful.
I don't like the idea of wrapping everything in a try
/catch
, and picking up a failed JSON.parse. We are already being given information on whether response.data
is an object or not, so let's use that.
You could even write a wrapper for Axios
That could do the above, so you only have to write the code once.