Last updated: Mar 2, 2024
Reading time·2 min
The "response.json is not a function" error occurs when:
json()
method on an object that is not the Response
object
that resolves from the promise the fetch()
method returns.json()
method on the return value of calling an axios
method.json()
method on a valid Response
objectTo solve the error, make sure to only call the json()
method on the Response
object that resolves from a valid call to the fetch()
method.
async function getUser() { try { const response = await fetch('https://randomuser.me/api/'); if (!response.ok) { throw new Error(`Error! status: ${response.status}`); } // ✅ call response.json() here const result = await response.json(); return result; } catch (err) { console.log(err); } } getUser().then(res => { console.log(res); });
The code sample shows a complete example of using the fetch() method to make a call to a remote API.
And here is an example of calling the response.json()
method if you use the
.then()
syntax.
function getUser() { return ( fetch('https://randomuser.me/api/') // ✅ call response.json() here .then(response => response.json()) .then(data => { console.log(data); }) .catch(err => { console.log(err); }) ); } getUser();
axios
, scroll down to the next subheading.The fetch()
method returns a Promise
that resolves to a Response
object.
The Response
object contains the json()
method that returns a promise that
resolves to a JavaScript object.
The json() method parses the JSON from the response to a native JavaScript object.
axios
If you use axios
, you don't have to call the json()
method on the response.
import axios from 'axios'; async function getUser() { try { const response = await axios.get( 'https://randomuser.me/api/', { headers: {'Accept-Encoding': 'gzip,deflate,compress'}, }, ); return response.data; } catch (err) { console.log(err); } } getUser().then(response => { console.log(response); });
Axios takes care of parsing the response automatically, so we don't have to call any additional methods.
Access the data
property on the object to get the data from the response.
The data
property contains the response that was sent from the server.
Here is an example that uses the .then()
syntax instead of async/await
.
import axios from 'axios'; async function getUser() { return axios .get('https://randomuser.me/api/', { headers: {'Accept-Encoding': 'gzip,deflate,compress'}, }) .then(response => { console.log(response.data); }) .catch(err => { console.log(err); }); } getUser().then(res => { console.log(res); });
Other properties on the axios
response object include:
status
- the status code of the server responsestatusText
- the HTTP status message of the response, e.g. OK
headers
- the HTTP headers the server responded withconfig
- the config that was provided to axios
for the requestrequest
- the request that generated this responseYou can learn more about the related topics by checking out the following tutorials: