fetch response.json() gives responseData = undefined

Solution 1:

The chaining response should look more like this, specifically the response.json part. Then you should get an Object back in console.log.

.then(response => response.json())
.then(response => {

    console.log(response)

}

Solution 2:

Fetch is a little hard to get your head around. I am new to this so dont shoot me down if flames here but response data is another promise and you need to return response data and then handle that promise with yet another then statement where you can finally log the response, also your are missing some return statements in your promises:

var makeRequest = function(){

    fetch('https://jsonplaceholder.typicode.com/posts/1', {
        method: 'get',
        dataType: 'jsonp',
        headers: {
           'Accept': 'application/json',
           'Content-Type': 'application/json'
        }
    })
    .then((response) => {
       return response.json() // << This is the problem
    })
    .then((responseData) => { // responseData = undefined
        addTestToPage(responseData.title);
        return responseData;
    })
  .catch(function(err) {
      console.log(err);
  })
}

function addTestToPage(textToAdd){
   var para = document.createElement("p");
   var node = document.createTextNode(textToAdd);
   para.appendChild(node);

  var element = document.getElementsByTagName("body")[0];
  element.appendChild(para);
}

makeRequest();

hope that helps see: https://jsfiddle.net/byz17L4L/

Solution 3:

Here's how it finally worked out in my case:

fetch('http://localhost:3001/questions', {
        method: 'GET',
        headers: {
        "Accept": "application/json",
        'Content-Type': 'application/json'
        }
    })
    .then(response => { return response.json();})
    .then(responseData => {console.log(responseData); return responseData;})
    .then(data => {this.setState({"questions" : data});})

    .catch(err => {
        console.log("fetch error" + err);
    });
}

Solution 4:

because you didn't return response.json() in the first then.

Solution 5:

import React, {useEffect} from 'react';

useEffect(() => {
    getRecipes();
  }, []);

  const getRecipes = async () => {
    const response = await fetch(
      `https://........`
    );
    const data = await response.json();
    console.log(data);
  • Use this method You can easily fatch data.