javascript - React Native fetch api 在转换为 json 之前检查 http 状态

标签 javascript reactjs react-native

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

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

我的获取代码如下所示:

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 的文档,你会看到这个:

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.

再往下:

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 正文转换之前先检查状态。类似于以下内容:

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

关于javascript - React Native fetch api 在转换为 json 之前检查 http 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50076201/

相关文章:

react-native - 使用 babel-module-resolver 从单个文件导出时出现循环依赖问题

arrays - React Native 对象子映射在父映射内

javascript - 在 Google 图表中显示单位

javascript - jQuery 如何在点击时中断 .load() ?

javascript - 使用输入中的文本添加多种样式的 div

javascript - 如何为嵌套对象设置状态?

javascript - 根据当前旋转顺时针或逆时针旋转 div

JavaScript - Node.js 错误 : Can't set headers after they are sent

javascript - 如何用 ReactJS 中的变量替换查询参数中的字符串

javascript - React Native 不支持在 Windows 上开发(还)?