Solve - response.json is not a function TypError in JS

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by Jonatan Pie

Solve - response.json is not a function TypError #

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.

typeerror response json is not a function

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.

index.js
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.

If you're using axios scroll down to the next code snippet.

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 JavaScript object contains the value that was returned from the remote API call.

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.

index.js
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 response
  • statusText - the HTTP status message of the response, e.g. OK
  • headers - the HTTP headers the server responded with
  • config - the config that was provided to axios for the request
  • request - the request that generated this response

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee