Borislav Hadzhiev
Tue Oct 19 2021·2 min read
Photo by Jonatan Pie
The "response.json is not a function" error occurs when we call the json()
method on an object that is not the Response
object that resolves from the
promise the fetch()
method returns, or call the json()
method on the return
value from calling an axios
method.
To solve the "response.json is not a function" 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}`); } const result = await response.json(); return result; } catch (err) { console.log(err); } } console.log(await getUser())
The code snippet shows a complete example of using the fetch() method to make a call to a remote API.
The fetch()
method returns a Promise
that response to a Response
object.
The Response
object contains the json()
method, which returns a promise that
resolves to a JavaScript object.
The json() method basically parses the JSON from the response to a native JavaScript object.
If you're using axios, you shouldn't call the json()
method on the return
value. Here is a complete example.
import axios from 'axios'; async function getUser() { try { const response = await axios.get('https://randomuser.me/api/'); return response.data; } catch (err) { console.log(err); } } console.log(await getUser());
Axios takes care of parsing the response automatically for us, so we don't have to call any additional methods.
To get the data
from the response, simply access the data
property on the
object the axios.get
method returns.
The data
property contains the response that was sent from the server.
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 response