【问题标题】:Fetch with react native使用本机反应获取
【发布时间】:2017-11-22 15:01:22
【问题描述】:

我在 React Native 中使用 fetch 来调用我的 API,但是,它只有 75% 的时间有效。 当我的请求不起作用时,我会得到这个:

TypeError:网络请求失败

SyntaxError: Unexpected token

fetch('http://localhost/vision.php', {
      method: 'POST',
      headers: {
          'Accept': 'application.json',
          'Content-Type': 'application.json',
      },
      body: JSON.stringify({
          key: 'Mon paramètre'
      })
    })
    .then((data) => data.json())
    .then((dataJson) => {
        console.log(dataJson.message);
    })
    .catch((error) => {
         console.log(error);
    });

}

谁能解释一下?

【问题讨论】:

  • 如果你在这一行后面加上“if (dataJson !== null) {...”:“.then((dataJson) => {”,它仍然会发生吗?

标签: api react-native fetch fetch-api


【解决方案1】:

当你得到TypeError: Network request failed时,这意味着,嗯,网络请求失败了。 可能意味着您尝试连接的 API/服务器已关闭/不再监听连接。

关于SyntaxError: Unexpected token < in JSON at position 0,这就是您在尝试将非 JSON 解析为 JSON 时得到的结果。通常在这里,您的 API / 服务器可能无法满足您的请求,而不是 JSON,而是为您提供 HTML 错误页面。

在尝试解析 JSON 响应 (data.json()) 之前,您可能需要检查 data.ok 是否为 true

【讨论】:

  • 好的,谢谢,但它是带有谷歌服务器的 API google,所以我认为它没有关闭,但对于 JSON 来说还可以
  • 更新了我的答案以反映它可能是它。
猜你喜欢
  • 1970-01-01
  • 2016-05-25
  • 2018-07-31
  • 1970-01-01
  • 1970-01-01
  • 2018-03-06
  • 2017-10-10
  • 2019-02-05
  • 2019-03-19
相关资源
最近更新 更多