简体   繁体   English

在前端或后端缓存

[英]Caching on frontend or on backend

Right now I send my requests via ajax to the backend server, which does some operations, and returns a response:现在我通过 ajax 将我的请求发送到后端服务器,它执行一些操作,并返回一个响应:

function getData() {
  new Ajax().getResponse()
    .then(function (response) {
      // handle response
    })
    .catch(function (error) {
      // handle error
    });
}

The thing is that each time a user refreshes the website, every request is sent again.问题是每次用户刷新网站时,都会再次发送每个请求。 I've been thinking about caching them inside the local storage:我一直在考虑将它们缓存在本地存储中:

function getData() {
  if (Cache.get('getResponse')) {
    let response = Cache.get('getResponse');
    // handle response
    return true;
  }
  new Ajax().getResponse()
    .then(function (response) {
      // handle response
    })
    .catch(function (error) {
      // handle error
    });
}

This way if a user already made a request, and the response is cached inside the localStorage, I don't have to fetch data from the server.这样,如果用户已经发出请求,并且响应缓存在 localStorage 中,我就不必从服务器获取数据。 If a user changes values from the getResponse , I would just clear the cache.如果用户从getResponse更改值,我只会清除缓存。


Is this a good approach?这是一个好方法吗? If it is, is there a better way to do this?如果是,有没有更好的方法来做到这一点? Also, should I cache backend responses the same way?另外,我应该以相同的方式缓存后端响应吗? What's the difference between frontend and backend caching?前端缓存和后端缓存有什么区别?

Is this a good approach?这是一个好方法吗? It depends on what kind of data you are storing这取决于您存储的数据类型

Be aware that everything stored on frontend can be changed by the user so this is potential security vulnerability.请注意,用户可以更改前端存储的所有内容,因此这是潜在的安全漏洞。

This is the main difference between backend and frontend caching, backend caching can't be edited by the user.这是后端和前端缓存之间的主要区别,后端缓存不能由用户编辑。

If you decide to do frontend caching here is a code how to do it:如果您决定进行前端缓存,这里是一个代码如何做到这一点:

localStorage.setItem('getResponse', JSON.stringify(response));

For retrieving stored data from local storage用于从本地存储中检索存储的数据

var retrievedObject = localStorage.getItem('getResponse');

NOTE:笔记:

I assume that you are storing object not a string or integer .我假设您存储的是object 而不是 string 或 integer If you are storing a string, integer, float... Just remove JSON.stringify如果您要存储字符串、整数、浮点数...只需删除 JSON.stringify

The best practice is to use The Cache API "a system for storing and retrieving network requests and their corresponding responses".最佳实践是使用Cache API “一个用于存储和检索网络请求及其相应响应的系统”。

The Cache API is available in all modern browsers. Cache API 适用于所有现代浏览器。 It is exposed via the global caches property, so you can test for the presence of the API with a simple feature detection:它通过全局缓存属性公开,因此您可以通过简单的功能检测来测试 API 的存在:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM