【问题标题】:React Native fetch returns error: JSON Unexpected EOFReact Native fetch 返回错误:JSON Unexpected EOF
【发布时间】:2017-11-22 15:32:20
【问题描述】:

我希望这里有人可以帮助我解决这个问题。我已经与这个错误作斗争太久了。

我正在向传感器的 API 发出获取请求,这始终导致相同的错误:JSON Parse error: Unexpected EOF

我尝试在网上找到答案并尝试了很多建议,但都没有奏效。

在开发环境中,我通过本地网络访问 API。

fetchUsers(timer) {
    let data = {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json; charset=utf-8',
            'Authorization': 'Bearer ' + this.state.token.access_token
        }
    }
    fetch('http://' + this.state.ip + ':5000/api/Devices/031.01.0657/LiveState', data)
        .then(response => response.json())
        .then(responseJson => {
            this.setState({
                isLoading: false,
                error: false,
                userDataSource: responseJson,
                refreshing: false,
                time: timer
            }, function () {
                // If success, do something (I never make it to this part)
            });
        })
        .catch(error => {
            this.setState({
                isLoading: false,
                error: true
            })
            console.error(error);
        });
}

我当然一直在使用其他方式来查看 API 返回的内容:

我在使用 API 接口时得到响应的 JSON:

{
    "device": null,
    "patient": null
}

我在使用 Postman 客户端时收到的 JSON 响应:

{
    "device": null,
    "patient": null
}

使用与代码中完全相同的 URL。返回的 JSON 也作为有效 JSON 传递。

【问题讨论】:

    标签: json react-native fetch eof


    【解决方案1】:

    我想它在这一行失败了:response.json(). 你可以在尝试转换之前看到响应的内容:

    .then(response => {
        console.log(JSON.stringify(response, null, 4))
        return response.json())
    }
    

    我不确定

    JSON 中的值。我认为你应该使用

    “空”

    希望对你有帮助!

    【讨论】:

      【解决方案2】:

      只要在被抛出的那一行捕获错误就可以了。问题是 response.json 为空

      try {
        responseData = await response.json();
      } catch (e) {
          dispatch({ type: XXX_SSSSS, service: null });
      }
      

      【讨论】:

        【解决方案3】:

        我在使用 fetch 上传图像时遇到了同样的问题,它在调试时工作正常,但是当我发布时给出了同样的错误 尝试安装 npm install react-native-url-polyfill 并在 app.js 中导入“react-native-url-polyfill/auto”

        【讨论】:

          猜你喜欢
          • 2020-05-25
          • 2018-03-01
          • 2021-11-04
          • 1970-01-01
          • 2018-03-14
          • 2019-07-03
          • 2018-11-12
          • 2020-12-02
          • 1970-01-01
          相关资源
          最近更新 更多