【问题标题】:React Native: Log wrong responsesReact Native:记录错误的响应
【发布时间】:2017-09-22 12:33:45
【问题描述】:

如何在 fetch 语句中记录错误响应?
我的代码如下所示:

eturn fetch('myurl.com', {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
    }).then((response) => response.json())
        .then((responseData) => {
            console.log(responseData); // This logs nothing
        }).catch((error) => {
            console.log("Error " + error); // This logs something
        });

我的代码示例中的日志是Error SyntaxError: JSON Parse error: Unrecognized token '<'。我认为这是因为 XDebug 发送了一些错误消息,但我绝对不知道可能出了什么问题。看起来响应以'

是否可以显示此响应?这对找出我的错误非常有用。

【问题讨论】:

  • 为了调试去掉.then((response) => response.json())部分,调试后把它带回来

标签: react-native error-handling fetch xdebug


【解决方案1】:

试试这个并确保 url 返回正确的 json 格式:

    fetch(url)
        .then(res => res.json())
        .then(res => {
            this.setState({
                loading: false,
                data: res.data
            }, () => {
                console.log("log something")
            });
        })
        .catch(error => {
            console.log(error);
            this.setState({ loading:false, error });
        });

【讨论】:

  • 这是我的问题。我不想看到 exactly url 返回什么,因为在调试 url 后面的 PHP 代码时我找不到任何问题。使用您的代码,我得到了完全相同的错误。 Error SyntaxError: JSON Parse error: Unrecognized token '<'
  • 这意味着您的网址不会返回 json。删除第一行 .then 并重试?并使用 data: res 而不是 data: res.data。如果您确定您的网址返回 json,则保留第一行 .then 并执行 console.log(res)
  • 我很确定 url 不会返回正确的 json 格式。请提供网址以便我们提供帮助。
猜你喜欢
  • 1970-01-01
  • 2016-02-11
  • 1970-01-01
  • 1970-01-01
  • 2017-09-21
  • 2017-11-02
  • 2021-06-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多