Javascript fetch(),你如何发出一个非缓存的请求?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29246444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
fetch(), how do you make a non-cached request?
提问by cc young
with fetch('somefile.json'), it is possible to request that the file be fetched from the server and not from the browser cache?
用fetch('somefile.json'),也可以请求该文件是从服务器获取,而不是从浏览器缓存?
in other words, with fetch(), is it possible to circumvent the browser's cache?
换句话说,使用fetch(),是否可以绕过浏览器的缓存?
回答by burningfuses
Fetchcan take an init object containing many custom settings that you might want to apply to the request, this includes an option called "headers".
Fetch可以接受一个包含许多您可能想要应用于请求的自定义设置的 init 对象,这包括一个名为“headers”的选项。
The "headers" option takes a Headerobject. This object allows you to configure the headers you want to add to your request.
“headers”选项采用Header对象。此对象允许您配置要添加到请求中的标头。
By adding pragma: no-cacheand a cache-control: no-cacheto your header you will force the browser to check the server to see if the file is different from the file it already has in the cache. You could also use cache-control: no-storeas it simply disallows the browser and all intermediate caches to store any version of the returned response.
通过将pragma: no-cache和cache-control: no-cache 添加到您的标题中,您将强制浏览器检查服务器以查看该文件是否与缓存中已有的文件不同。您还可以使用cache-control: no-store因为它只是禁止浏览器和所有中间缓存存储返回响应的任何版本。
Here is a sample code:
这是一个示例代码:
var myImage = document.querySelector('img');
var myHeaders = new Headers();
myHeaders.append('pragma', 'no-cache');
myHeaders.append('cache-control', 'no-cache');
var myInit = {
method: 'GET',
headers: myHeaders,
};
var myRequest = new Request('myImage.jpg');
fetch(myRequest, myInit)
.then(function(response) {
return response.blob();
})
.then(function(response) {
var objectURL = URL.createObjectURL(response);
myImage.src = objectURL;
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ES6</title>
</head>
<body>
<img src="">
</body>
</html>
Hope this helps.
希望这可以帮助。
回答by MJ Vakili
Easier use of cache modes:
更容易使用缓存模式:
// Download a resource with cache busting, to bypass the cache
// completely.
fetch("some.json", {cache: "no-store"})
.then(function(response) { /* consume the response */ });
// Download a resource with cache busting, but update the HTTP
// cache with the downloaded resource.
fetch("some.json", {cache: "reload"})
.then(function(response) { /* consume the response */ });
// Download a resource with cache busting when dealing with a
// properly configured server that will send the correct ETag
// and Date headers and properly handle If-Modified-Since and
// If-None-Match request headers, therefore we can rely on the
// validation to guarantee a fresh response.
fetch("some.json", {cache: "no-cache"})
.then(function(response) { /* consume the response */ });
// Download a resource with economics in mind! Prefer a cached
// albeit stale response to conserve as much bandwidth as possible.
fetch("some.json", {cache: "force-cache"})
.then(function(response) { /* consume the response */ });
refrence:https://hacks.mozilla.org/2016/03/referrer-and-cache-control-apis-for-fetch/
参考:https: //hacks.mozilla.org/2016/03/referrer-and-cache-control-apis-for-fetch/
回答by Agu Dondo
You can set 'Cache-Control': 'no-cache'in the header like this::
您可以'Cache-Control': 'no-cache'像这样在标题中设置::
return fetch(url, {
headers: {
'Cache-Control': 'no-cache'
}
}).then(function (res) {
return res.json();
}).catch(function(error) {
console.warn('Failed: ', error);
});
回答by bbarker
None of the solutions seemed to work well for me, but this relatively clean (AFAICT) hack did work (adapted from https://webmasters.stackexchange.com/questions/93594/prevent-browser-from-caching-text-file):
没有一个解决方案对我来说似乎效果很好,但是这个相对干净(AFAICT)的 hack 确实有效(改编自https://webmasters.stackexchange.com/questions/93594/prevent-browser-from-caching-text-file) :
const URL = "http://example.com";
const ms = Date.now();
const data = await fetch(URL+"?dummy="+ms)
.catch(er => game_log(er.message))
.then(response => response.text());
This is just adding a dummy parameter that changes on every call to a query. By all means, if other solutions appear to work, I suggest using those, but in my tests, they did not work in my case (e.g. those using Cache-Controland pragram).
这只是添加了一个虚拟参数,该参数在每次调用查询时都会发生变化。无论如何,如果其他解决方案似乎有效,我建议使用这些解决方案,但在我的测试中,它们在我的情况下不起作用(例如那些使用Cache-Control和pragram)。

