【问题标题】:Using fetch() with API将 fetch() 与 API 一起使用
【发布时间】:2019-06-19 14:54:59
【问题描述】:

我尝试使用 fetch() 从https://swapi.co/ 获取数据 使用此代码,我得到未定义,但在 chrome 的“网络”部分中,我看到了我需要的数据。我如何访问它?

fetch('https://swapi.co/api/people/1/')
.then(resp => resp.json)
.then(obj => console.log(obj));

【问题讨论】:

    标签: api fetch


    【解决方案1】:

    您好,这将获取以 json 格式返回的数据

    fetch('https://swapi.co/api/people/1')
      .then(function(response) {
        return response.json();
      })
      .then(function(myJson) {
        console.log(JSON.stringify(myJson));
      });

    【讨论】:

      【解决方案2】:

      如果你有正确的环境来调用 fetch API,那么可能有 2 个结果

      1. 您将获得正确的结果数据

      2. 你会得到一个错误

        fetch(url) // Call the fetch function passing the url of the API as a parameter
        .then(function() {
                        // Your code for handling the data you get from the API
        })
        .catch (function() {
                        // This is where you run code if the server returns any errors
        });
        

      使用 catch 查看您的请求出了什么问题

      【讨论】:

      • 我在 chrome 的“控制台”部分得到:ƒ json() { [native code] },这意味着我得到了一个结果,但我不明白如何访问我在其中看到的数据chrome 中的“网络”部分。
      • 好的,我理解你。在 chrome 中没问题,但您的客户端有错误。渔获会告诉你什么是理由。在捕获时对其进行调试。例如它可能需要一个额外的 toJson 但你必须通过看到异常来确定
      • 我的朋友感谢您的帮助。我的错误是我忘记在 resp.json() 中使用 ()。
      • 那是额外的 toJson :)
      猜你喜欢
      • 2019-03-14
      • 2017-11-25
      • 1970-01-01
      • 2017-09-29
      • 1970-01-01
      • 2021-06-11
      • 2021-02-17
      • 1970-01-01
      • 2019-08-02
      相关资源
      最近更新 更多