如何从提取API返回json响应 [英] How to return the json response from the fetch API

查看:127
本文介绍了如何从提取API返回json响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的功能:

I have a function like so:

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;
    });
  }

然后我尝试执行此操作:

And then I try to do this:

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

但是,this.check_auth()始终是undefined.

我在这里想念什么?我以为在fetch的then()中是 resolved Promise对象所在的位置,因此我以为在用户登录时会得到true.但是事实并非如此.

What am I missing here? I thought that within fetch's then() was where the resolved Promise object was therefore I thought that I'd get true when the user was logged in. But this is not the case.

任何帮助将不胜感激.

推荐答案

使用回调

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中,它应该更易于处理,您可以调用fetch并更新状态,因为在每次使用setState更新状态时,都会调用render方法来渲染状态

In React it should be easier to handle, You can call a fetch and update the state, since on every update of state using setState the render method is called you can use the state to render

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});
    });
  }

这篇关于如何从提取API返回json响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆