fetch response.json() gives responseData = undefined

前端 未结 6 859
青春惊慌失措
青春惊慌失措 2020-12-01 06:34

When using fetch:

  fetch(REQUEST_URL, {
      method: \'get\',
      dataType: \'json\',
      headers: {
        \'Accept\': \'application/json\',
             


        
6条回答
  •  伪装坚强ぢ
    2020-12-01 06:50

    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/

提交回复
热议问题