【问题标题】:How do i get the status of my response when using fetch in react-native?在 react-native 中使用 fetch 时如何获取响应的状态?
【发布时间】:2017-02-07 13:16:45
【问题描述】:

我正在为我的 react native 应用程序制作登录页面。当我的用户名和密码有效和无效时,我的 api 会发送不同的响应。所以我想跟踪我的响应状态并将其保存在某个状态变量中,然后相应地执行功能。请建议我这样做。

  doSignUp() {
   console.log("inside post api");
   fetch('MyApiUrl', {
      method: 'POST',
      headers: {
                 'Accept': 'application/json',
                 'Content-Type': 'application/json',

                },


      body: JSON.stringify({
      password: this.state.password,
      email:this.state.email,
      name: this.state.firstname,
      last_name :this.state.last_name,
      mobile:this.state.mobile,
      ssn:"2222222"

     })
      }).then((response) => {console.log('response:',response.status);
             response.json()}
        .then((responseData) => {
                                console.log("inside responsejson");
                                console.log('response object:',responseData)
                                console.log('refresh token:',responseData[0].token.refresh_token)
                                console.log('access token:',responseData[0].token.access_token);



         }).done();

}

【问题讨论】:

    标签: react-native fetch-api


    【解决方案1】:

    据我了解,您想知道获取请求的 http 状态代码。

    通常您的响应对象包含一个“状态”属性。所以你应该可以使用这个来接收状态码:

    response.status
    

    如果请求成功,则返回 200。

    【讨论】:

    • 似乎我在您测试时编辑了答案,状态属性在您的第一个 .then() 回调的响应属性中可用
    • 是的,我编辑了上面的代码。现在我得到的问题是 responseData 不是 json 格式,这一定是由于我认为异步回调代码而发生的,请建议我采取一些方法来做到这一点。我在控制台上收到的输出是 ----> 在 post api SignUp.js:35 response: 201 SignUp.js:39 inside responsejson SignUp.js:40 response object: undefined ExceptionsManager.js:61 Cannot read property ' 0' of undefined @manpenaloza
    • 我的目标是获取状态码,如果成功则只有我会保存访问令牌,否则我会显示无效用户名/密码的消息。 @manpenaloza
    猜你喜欢
    • 1970-01-01
    • 2021-02-28
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 2021-02-26
    相关资源
    最近更新 更多