NestJS returning the result of an HTTP request
This issue comes from the axios library. In order to fix that, you have to pull out the data
property:
return this.httpService.post(...)
.pipe(
map(response => response.data),
);
The problem seems to stem from the fact that we are trying to return a Response object directly, and that is circular by nature. I'm not sure of the correct way to implement this, but I was able to get around it by using axios directly, unwrapping the promise and returning just the data.
@Post('login')
async authenticateUser(@Body() LoginDto) {
const params = JSON.stringify(LoginDto);
return await axios.post('https://api.example.com/authenticate_user',
params,
{
headers: {
'Content-Type': 'application/json',
},
}).then((res) => {
return res.data;
});
}
UPDATE
I realized I could just do the same thing to the Observable being returned from the httpService
using the new rxjs pipe method, so that's probably the better way to do it.
@Post('login')
async authenticateUser(@Body() LoginDto) {
const params = JSON.stringify(LoginDto);
return this.httpService.post('https://api.example.com/authenticate_user',
params,
{
headers: {
'Content-Type': 'application/json',
},
}).pipe(map((res) => {
return res.data;
}));
}