所以我正在尝试从 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/