【问题标题】:Odd response from Github API (Conditional requests)来自 Github API 的奇怪响应(条件请求)
【发布时间】:2020-12-04 05:09:09
【问题描述】:

所以我正在尝试从 Github API 中检索 React 应用程序的 repo 数据。由于 API 的速率限制,我尝试使用 conditional requests 来检查自上次请求以来数据是否已被修改,使用 If-Modified-Since 标头。

这是我目前的测试代码:

const date = new Date().toUTCString();


fetch('https://api.github.com/users/joshlucpoll/repos', {
  headers: {'If-Modified-Since': date}
  })
  .then((res) => {
    let headers = res.headers;
    console.log(headers)
    if (headers.get('status') === "304 Not Modified") {
      console.log("Not modified")
    }
    else {
      console.log("modified")
    }
  });

每次运行此代码时,我都会得到一个200 OK 状态,而不是预期的304 Not Modified。资源在运行代码时无法更新,但是,它总是输出“未修改”...

我不明白为什么这不起作用,我们将不胜感激!

【问题讨论】:

    标签: javascript github-api response-headers


    【解决方案1】:

    这里的问题是您处理状态的方式。

    这里是关于它应该如何实现的一些设置:https://codesandbox.io/s/wizardly-banzai-pi8to?file=/src/index.js

    const date = new Date().toUTCString();
    
    fetch("https://api.github.com/users/joshlucpoll/repos", {
      headers: { "If-Modified-Since": date }
    }).then((res) => {
      console.log(res.status);
    });
    

    状态可以在响应本身中检索,它不嵌套在标头中。

    你会看到res.status的值为304,res.headers.get("status")会返回null

    【讨论】:

      猜你喜欢
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-17
      • 2017-09-04
      • 2020-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多