react native fetch api 在转换为 json 之前检查 http 状态 [英] react native fetch api check http status before converting to json

查看:57
本文介绍了react native fetch api 在转换为 json 之前检查 http 状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码正在发出ajax请求并获取数据.如您所见,then((response) => response.json()) 是将响应转换为 json.但是如果 http 状态未授权或其他(400、401 等)并且没有返回 json 数据怎么办.在将响应转换为 json 之前,有没有更好的方法来检查状态代码?

Below code is making ajax request and getting data. As you can see then((response) => response.json()) is to convert response to json. But what if the http status is unauthorized or something else (400, 401 etc) and no json data is returned. Is there any better way to check status code before I convert the response to json?

我想 catch 是我可以做到这一点的地方,但是,我想为未处理的异常保留 catch.基于状态代码,我想显示用户收到的确切错误(当然出于安全原因不适用于登录组件).例如,无效授权、无效令牌.

I guess the catch is where I can do this, however, I want to keep catch for unhandled exceptions. Based on the status code I would like to show exact error user received(of course not for login component for security reasons). For example, Invalid Authorization, Invalid token.

我的提取代码如下所示:

My fetch code looks like this:

onLoginPressed() {

    fetch('http://localhost:8080/api/user/login', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            username: this.state.username,
            password: this.state.password
        })
    }).then((response) => response.json())
        .then((responseJson) => {

            if (responseJson.status === 500) {
                Alert.alert(responseJson.message);
            } else if(responseJson.profileCompleted == false){
                this.props.navigation.navigate('SetupOne');
            } else {
                this.props.navigation.navigate('Home');
            }

        }).catch((error) => {
        console.error(error);
    });
}

推荐答案

如果您查看 fetch,你会看到:

If you look at the docs for fetch, you will see this:

即使响应是 HTTP 404 或 500,从 fetch() 返回的 Promise 也不会拒绝 HTTP 错误状态.相反,它将正常解析(ok 状态设置为 false),并且只会拒绝网络故障或是否有任何原因导致请求无法完成.

The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.

再往下:

对成功 fetch() 的准确检查包括检查 promise 是否已解决,然后检查 Response.ok 属性的值是否为 true.

An accurate check for a successful fetch() would include checking that the promise resolved, then checking that the Response.ok property has a value of true.

所以换句话说,如果这与您有关,您可能希望在进行 json 正文转换之前先检查状态.类似于以下内容:

So in other words, if this concerns you, you might want to check the status first, before doing your json body conversion. Something like the following:

const handleResponse = res => {
  if(res.ok) {
    return res.json()
  }
  throw new Error('Network response was not ok.')
}

fetch(someUrl, details)
  .then(handleResponse)      
  .then(doYourWorkWithJSON)
  .catch(err => console.error(err))

这篇关于react native fetch api 在转换为 json 之前检查 http 状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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