【问题标题】:Unable to fetch data from Redis in NestJS application无法从 NestJS 应用程序中的 Redis 获取数据
【发布时间】:2022-02-20 03:00:48
【问题描述】:

我将密钥存储在 redis 中,我试图在嵌套应用程序中获取值,但它在控制台中显示错误:

SyntaxError: Unexpected token d in JSON at position 0

在 postmna 中,它的响应显示为空 json 对象,例如 { } 为什么如果 redis 中的键可用,则会显示空对象

下面是我的代码:

phone.dto.ts

import { IsNotEmpty, MinLength } from "class-validator";

export class PhoneNumber 
{
 @IsNotEmpty({message: 'Phone number cannot be empty'})
 @MinLength(10, {message: 'Invalid phone number'}) 
 phoneNumber:string;
}

subscribe.controller.ts

@Post('location')
async getLocation(@Body(ValidationPipe) phoneNumber:PhoneNumber){
    const loc = await this.subscribeService.getLocation(phoneNumber);
    return loc; 
}

subscribe.service.ts'

 async getLocation(phoneNumber:PhoneNumber){
   
    try{

        console.log(phoneNumber.phoneNumber);
        
        const valu = await this.cacheManager.get(phoneNumber.phoneNumber);
      
        if(valu){
            return valu; 
        }
        else{
            return 'No key found';
        }
      }
     catch(err){
        console.log(err); 
        return err;
     }
 }

有人告诉我为什么我会遇到这个问题。

【问题讨论】:

    标签: node.js redis nestjs


    【解决方案1】:

    您可以添加数据作为键:

    async getLocation(phoneNumber:PhoneNumber){   
    try{
    
        console.log(phoneNumber.phoneNumber);
        
        const valu = await this.cacheManager.get(phoneNumber.phoneNumber);
      
        if(valu){
            return {data:valu}; //like this
        }
        else{
            return 'No key found';
        }
      }
     catch(err){
        console.log(err); 
        return err;
     }
    }
    

    如果有用,请点赞:)

    【讨论】:

      猜你喜欢
      • 2017-08-31
      • 2020-09-30
      • 2021-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-18
      • 2021-09-09
      • 1970-01-01
      相关资源
      最近更新 更多