来自 Github API 的奇怪响应(有条件的请求)
Odd response from Github API (Conditional requests)
所以我正在尝试从 Github API 中检索 React 应用程序的回购数据。由于 API 上的 rate-limiting,我正在尝试使用 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);
});
可以在响应本身中检索状态,它不嵌套在 headers 中。
你会看到res.status
的值为304,res.headers.get("status")
会return为null
所以我正在尝试从 Github API 中检索 React 应用程序的回购数据。由于 API 上的 rate-limiting,我正在尝试使用 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);
});
可以在响应本身中检索状态,它不嵌套在 headers 中。
你会看到res.status
的值为304,res.headers.get("status")
会return为null