我使用node-cache-manager来管理Node.js缓存。
我已经成功地向缓存中添加了一个项:
import cacheManager from 'cache-manager';
const memoryCache = cacheManager.caching({store: 'memory', max: 100, ttl: 3600/*seconds*/});
memoryCache.set('testItem', { 'key': 'testValue'}, {ttl: 36000}, (err) => {
if (err) { throw err; }
});但是,当我想从缓存中检索一个项目时,它会用Result: [Object Object]响应
代码如下:
let cacheResult = await memoryCache.get('testItem');
console.log('Result: ' + { cacheResult });发布于 2020-12-29 07:06:31
你好啊!
您已经将变量定义为JSON对象,因此Javascript将其视为对象。
为了避免这种情况,您必须将JSON对象转换为字符串,您必须这样做:
memoryCache.set('testItem', JSON.stringify({ 'key': 'testValue'}), {ttl: 36000}, (err) => {
if (err) { throw err; }
});当您想要检索变量的内容时
let cacheResult = await JSON.parse(memoryCache.get('testItem'), true);实例性示例:
var json = JSON.stringify({"name":"John", "age":30, "city":"New York"});
var obj = JSON.parse(json, true);
console.log(obj);
console.log('Name of user: ' + obj.name)
https://stackoverflow.com/questions/65485041
复制相似问题