如何使用JavaScript缓存API保存缓存存储日期?



我正在使用JavaScript的Cache Web API来存储从我的服务器到我的客户端应用程序发出的请求的响应。此外,我需要一种方法来根据最初发出请求的时间以编程方式删除它们。以下是我用来存储响应的代码:

/** Searches for the corresponding cache for the given request. If found, returns
*  the cached response. Otherwise, performs the fetch request and adds the response
*  to cache. Returns the HTTP response.
*/
export async function fetchCachedData(request: Request) {
const cache = await caches.open(CACHE_NAME);
// Check if response is already cached
const cachedResponse = await cache.match(request);
if (cachedResponse) {
console.debug("Using cached response for", request.url);
return cachedResponse.clone();
}
// Fetch new response
console.debug("Fetching", request.url, "...");
const response = await fetchFromAPI(request);
const responseDate = new Date().getTime().toString();
response.headers.set("Date", responseDate);
// Cache the new response
if (
response.ok /*&& response.clone().headers.get("Cache-Control") !== "no-store"*/
) {
await cache.put(request, response.clone());
console.info("Cached response as", response.url);
}
return response.clone();
}

这种方法似乎适用于Firefox等浏览器,但是在Chrome上,我收到一个错误,告诉我headers是只读的:TypeError: Failed to execute 'set' on 'Headers': Headers are immutable

我还尝试在服务器端设置Date标头,但是在克隆和从缓存中检索它们时,似乎并非所有在基于 Express 的应用程序中设置的标头都得到支持。这就是为什么我希望在客户端检索响应时手动设置请求日期的原因。

我不一定需要将日期存储在缓存响应的标头中,这只是我设置缓存过滤代码的方式。理想情况下,请求日期应存储在响应对象中的某个位置,以便在使用clone()时保留它并存在于缓存中。

我已经通过使用编译指示 HTTP 标头解决了这个问题——它似乎在 HTTP/1.1 规范中未使用,但是当在服务器端设置时,它保留在从fetch()API 发出请求后获得的响应对象的标头中。

服务器代码(快速.js):

export function headerMiddleware(
_req: Request,
res: Response,
next: NextFunction
) {
const now = new Date().getTime();
res.setHeader("pragma", now);
next();
}

可能不鼓励这种实现,因为pragma是一个已弃用的标头,其初衷是指示no-cache是否是如何处理响应,但是当我将其值设置为数字字符串时,似乎没有错误并且解决方案运行顺利。理想情况下,我会使用Date标头,但是如果我在服务器端设置它,那么在客户端检查时会删除标头。

最新更新