javascript - 来自 Github API 的奇怪响应(条件请求)

标签 javascript github-api response-headers

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

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

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);
});

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

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

关于javascript - 来自 Github API 的奇怪响应(条件请求),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63410616/

相关文章:

javascript - Angular 1.0.1 与 1.3.0 的指令

javascript - 正则表达式: Match whole numbers in string

c# - 从 C# 6 中的响应 header 中删除 SERVER

go - 如何从http响应中提取某个 header [Set-Cookie]

javascript - node.js/ express : Can't set headers after they are sent

javascript - JSX css 到内联样式

javascript - 如何在 jQuery Ajax 中验证序列化表单?

github-api - 通过存储库调度事件触发时,如何在工作流中指定 event_type

node.js - 使用 Github API 时如何知道 mime 类型

python - 为什么用于内容更新的 Github API 会抛出 400 错误?