如何使用Nest.js中的axios HttpService发出POST请求 [英] How to use axios HttpService from Nest.js to make a POST request
本文介绍了如何使用Nest.js中的axios HttpService发出POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用@nestjs/axios
发出POST请求并返回响应。
这是我的代码:
verifyResponse(captcha_response: String): Observable<AxiosResponse<any>> {
return this.httpService.post('<url of rest endpoint to verify captcha>', {
captcha_response
});
}
但是,Visual Studio代码显示Cannot find name 'AxiosResponse'
。我可以从哪里进口这个?此类型在Nest.js docs中用作Observable<AxiosResponse<Cat[]>>
。我决定删除它,只使用类型Observable<any>
。
此方法有效。但是,如果我使用console.log()
查看响应,则会得到以下结果:
Observable { _subscribe: [Function (anonymous)] }
我在StackOverflow上找到的大多数答案都建议使用以下变体:
return this.httpService.post('<url of rest endpoint to verify captcha>', {
captcha_response
}).pipe(map(response => response.data));
.但是console.log()
给了我这个:
Observable {
source: Observable { _subscribe: [Function (anonymous)] },
operator: [Function (anonymous)]
}
有关StackOverflow的其他一些答案建议使用.toPromise()
,但显然已弃用。
推荐答案
如果要使HttpService
使用承诺而不是OnRxJS Observable,可以使用lastValueFrom
包装this.httpService.post()
调用。这将把可观察对象转换为承诺,您可以像往常一样await
它。否则,如果您只返回可观察对象,Nest将为您处理等待响应。无论哪种方式,您都需要确保使用您已有map((resp) => resp.data)
函数,这样您就不会在Response对象中得到循环数据(因为Axios的Response对象在设计上是循环的)。
如果您尝试console.log()
数据,则需要将tap
与map
一起使用,形式为
this.httpService.post(url, data, options).pipe(
tap((resp) => console.log(resp)),
map((resp) => resp.data),
tap((data) => console.log(data)),
);
tap
本质上是一种侦察方法,用于窃听可观测对象、查看数据并让其通过。它可以更改数据,但通常最好将其留给map
或其他rxjs operators。
仅对于简单的await
功能,就只需要这样的功能
const data = await lastValueFrom(
this.httpService.post(url, data, options).pipe(
map(resp => res.data)
)
);
对象类型(TypeScript)AxiosRequestConfig
示例
const requestConfig: AxiosRequestConfig = {
headers: {
'Content-Type': 'YOUR_CONTENT_TYPE_HEADER',
},
params: {
param1: 'YOUR_VALUE_HERE'
},
};
const responseData = await lastValueFrom(
this.httpService.post(requestUrl, null, requestConfig).pipe(
map((response) => {
return response.data;
}),
),
);
这篇关于如何使用Nest.js中的axios HttpService发出POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文