Github API的响应异常有条件的请求

问题描述

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

到目前为止,这是我的测试代码

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。资源在运行代码时无法更新,但是,它始终输出“未修改” ...

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

解决方法

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

这里有一些应如何实现的设置: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