如何从 fetch API 返回 json 响应

新手上路,请多包涵

我有这样的功能:

 check_auth(){
    fetch(Urls.check_auth(), {
      credentials: 'include',
      method: 'GET'
    }).then(response => {
      if(response.ok) return response.json();
    }).then(json => {
      return json.user_logged_in;
    });
  }

然后我尝试这样做:

 if(this.check_auth()){
    // do stuff
} else {
    // do other stuff
}

但是, this.check_auth() 总是 undefined

我在这里错过了什么?我认为在 fetch 的 then() 中是已 解析 的 Promise 对象所在的位置,因此我认为当用户登录时我会得到 true 。但事实并非如此。

任何帮助将不胜感激。

原文由 Brad Evans 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 577
1 个回答

使用回调

check_auth(callback){
    fetch(Urls.check_auth(), {
      credentials: 'include',
      method: 'GET'
    }).then(response => {
      if(response.ok) return response.json();
    }).then(json => {
      callback(json.user_logged_in);
    });
  }

 check_auth(function(data) {
        //processing the data
        console.log(d);
    });

在 React 中,它应该更容易处理,您可以调用获取并更新状态,因为在每次使用 setState 更新状态时,都会调用渲染方法,您可以使用状态来渲染

check_auth = () =>{
    fetch(Urls.check_auth(), {
      credentials: 'include',
      method: 'GET'
    }).then(response => {
      if(response.ok) return response.json();
    }).then(json => {
         this.setState({Result: json.user_logged_in});
    });
  }

原文由 Shubham Khatri 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题