fetch response.json()给出responseData = undefined

Chr*_* G. 36 react-native

使用fetch时:

  fetch(REQUEST_URL, {
      method: 'get',
      dataType: 'json',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    })
    .then((response) => 
      {
        response.json() // << This is the problem
      })
    .then((responseData) => { // responseData = undefined

        console.log(responseData);
     });
     }).catch(function(err) {
        console.log(err);
      })
     .done();
Run Code Online (Sandbox Code Playgroud)

以下作品有效,你知道为什么吗?:

    JSON.parse(response._bodyText)
Run Code Online (Sandbox Code Playgroud)

smo*_*re4 46

链接响应应该更像这样,特别是response.json部分.然后你应该Object回来console.log.

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

    console.log(response)

}
Run Code Online (Sandbox Code Playgroud)

  • 如果你用花括号做回调,你需要`return response.json()`.简化形式`response => response.json()`中有一个隐式的return语句. (10认同)
  • 我添加了`.then(response =&gt; response.json())`并且它起作用了。你能告诉我为什么在没有用的情况下添加它吗? (2认同)

And*_*ard 35

Fetch有点难以理解.我是新来的,所以不要把我击倒如果火焰在这里,但响应数据是另一个承诺,你需要返回响应数据然后处理该承诺与另一个然后声明,你可以最终记录响应,也是你缺少一些回报你的承诺中的陈述:

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();
Run Code Online (Sandbox Code Playgroud)

希望有助于看到:https://jsfiddle.net/byz17L4L/


小智 10

以下是它在我的案例中最终得到的结果:

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);
    });
}
Run Code Online (Sandbox Code Playgroud)


小智 9

因为你没有在第一个返回response.json().