如何在 NestJS 中使用基本身份验证?

问题描述

所以我正在尝试进行 API 调用,并且必须使用基本身份验证。

代码如下:

const headersRequest = {
    'Content-Type'  : 'application/json','Authorization' : `Basic ${this.authToken}`
}

let response = this.httpService.get(url,{headers: headersRequest});

问题是上面的get()函数调用正确吗?

因为输出

console.log(response)

是:

Observable { _isScalar: false,_subscribe: [Function (anonymous)] }

而不是我想要的响应对象。

我曾尝试探索 HttpService get,但找不到与此基本身份验证相关的任何详细文档。

PS:我是一名 PHP 开发人员,最近几天刚刚学习了 nestJS。

解决方法

在这种情况下,从 observable 中获得正确结果的最简单方法是将其转换为 promise。

const response = await this.httpService.get(url,{headers: headersRequest}).toPromise()