javascript - 在前端或后端缓存

标签 javascript ajax http caching

现在我通过 ajax 将请求发送到后端服务器,后端服务器执行一些操作并返回响应:

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

问题是每次用户刷新网站时,每个请求都会再次发送。我一直在考虑将它们缓存在本地存储中:

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
    });
}

这样,如果用户已经发出请求,并且响应缓存在 localStorage 中,我就不必从服务器获取数据。如果用户更改了 getResponse 的值,我会清除缓存。


这是一个好方法吗?如果是,是否有更好的方法来做到这一点?另外,我应该以同样的方式缓存后端响应吗?前端缓存和后端缓存有什么区别?

最佳答案

这是一个好方法吗? 这取决于您存储的数据类型

请注意,存储在前端的所有内容都可以由用户更改,因此这是潜在的安全漏洞。

这是后端缓存和前端缓存的主要区别,后端缓存不能被用户编辑。

如果你决定做前端缓存这里是一个代码如何做:

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

用于从本地存储中检索存储的数据

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

注意:

我假设您存储的是 object not a string or integer 。如果您要存储字符串、整数、 float ...只需删除 JSON.stringify

关于javascript - 在前端或后端缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41510722/

相关文章:

c# - 为什么 WCF 服务作为 PID 4 (SYSTEM) 而不是托管它的进程的 PID 进行监听?

javascript - AngularJS - 使用下拉菜单填充输入文本字段

javascript - 内容安全策略与可变内联样式(CSP 与 CSS)

javascript - Ajax获取的页面无法使用input type = "file"标签?

jquery - 使用网格系统构建 jQuery Mobile 照片库

c# - 为什么 IIS 返回空响应?

http - Chrome 和过期 header - 图像缓存

javascript - React.creatFactory 与 ES6 等效

javascript - contenteditable div 中突出显示的文本 : Get the start and the end of the highlighted text

php - 如何在 AJAX 实时聊天中实现聊天审核?