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



因此,我正在尝试从React应用程序的Github API检索回购数据。由于API的速率限制,我尝试使用条件请求来检查自上次请求以来数据是否已被修改,使用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状态。资源不可能在运行代码的时间内更新,但是,它总是输出";未修改";。。。

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

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

以下是关于如何实现它的一些设置: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")将返回空

最新更新