现在我通过 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/