无法从显示错误 412 的 NestJs 中的第 3 方 api 获取数据

Unable to fetch data from 3rd party api in NestJs showing Error 412

我正在尝试 post 向第三方发送数据 api 我已经在我的请求中正确添加了 authkey headers 但是当我发出请求时它显示以下错误:

 ERROR [ExceptionsHandler] Request failed with status code 412

下面是我的 postman 配置,用于发出 postman 请求:

下面是我的代码:

subscribe.controller.ts

@Controller()
export class SubscribeController {
constructor(private subscribeService:SubscribeService){}

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

subscribe.service.ts

@Injectable()
export class SubscribeService {
constructor(@InjectModel('Subscribe') private readonly model:Model<Subscribe>,
            private httpService: HttpService){}

    async getLocation(phoneNumber:string){
   
    const data = {phoneNumber};  

    const url = 'https://example.com';
    const headersRequest = {
      'Content-Type': 'application/json',
      'authkey': 'xxxxxxxxxxxx'
    };

      const resp = await this.httpService.post(url,data,{ headers: headersRequest }).pipe(
        map((response) => {
          return response.data;
        })
      );

      return resp;
   }
}

有人告诉我我做错了什么任何帮助将不胜感激。

另外我建议你像这样发送正文 创建以下 DTO class

    export class PhoneNumber 
    {
    phoneNumber:string
    }

然后,输入您的 API/controlloer

  @Post('location')
async getLocation(@Body() phoneNumberBody:PhoneNumber,
 @Headers('authkey') authkey:string)){
   
    const loc = await this.subscribeService.getLocation(phoneNumberBody,authkey);
    return loc; 
  }
} 

更新发送正文的服务,

@Injectable()
export class SubscribeService {
    constructor(@InjectModel('Subscribe') private readonly model:Model<Subscribe>,
                private httpService: HttpService){}

    async getLocation(phoneNumber:PhoneNumber,authkey:string){
        
        const url = 'https://example.com';
        const headersRequest = {
            'Content-Type': 'application/json',
            'authkey': authkey 
        };

        const resp = await this.httpService.post(url,phoneNumber,{ headers: headersRequest }).pipe(
            map((response) => {
                return response.data;
            })
        );

        return resp;
    }
}

为确保您以正确的格式发送正文,请尝试 console.log(phoneNumber); 在服务调用中

如果行不通,我们可以尝试使用 axios 请求的另一件事

  const resp = await axios.post('https:<your-url>',phoneNumber,{headers:{
            'Content-Type': 'application/json',
            'authkey': authkey
        }});

        console.log(resp.data);
     }
     catch(err){
         console.log(err);
     }