fetch(),你如何制作非缓存请求? [英] fetch(), how do you make a non-cached request?

查看:847
本文介绍了fetch(),你如何制作非缓存请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 fetch('somefile.json'),可以请求从服务器获取文件而不是从浏览器缓存中获取文件?



换句话说,使用 fetch(),是否有可能规避浏览器的缓存?

解决方案

抓取

a>可以接受一个init对象,该对象包含许多可能要应用于请求的自定义设置,其中包括一个名为headers的选项。



headers选项需要标题对象。此对象允许您配置要添加到请求中的标头。



通过添加 pragma:no-cache cache-control:no-cache 添加到您的头文件中,您将强制浏览器检查服务器以查看文件是否与缓存中已存在的文件不同。您还可以使用缓存控制:no-store ,因为它仅仅禁止浏览器和所有中间缓存存储返回的任何版本的响应。



<下面是一个示例代码:

< !DOCTYPE html>< html lang =en>< head> < meta charset =UTF-8> <标题> ES6< /标题>< /头><身体GT; < img src =>< / body>< / html>

b $ b

希望这有助于。


with fetch('somefile.json'), it is possible to request that the file be fetched from the server and not from the browser cache?

in other words, with fetch(), is it possible to circumvent the browser's cache?

解决方案

Fetch can take an init object containing many custom settings that you might want to apply to the request, this includes an option called "headers".

The "headers" option takes a Header object. This object allows you to configure the headers you want to add to your request.

By adding pragma: no-cache and a cache-control: no-cache to 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-store as it simply disallows the browser and all intermediate caches to store any version of the returned response.

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.

这篇关于fetch(),你如何制作非缓存请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆