25

I am trying to make a POST request using @nestjs/axios and then access the response.

This is my code so far:

verifyResponse(captcha_response: String): Observable<AxiosResponse<any>> {

    return this.httpService.post('some url', {
        captcha_response
    });
}

However, I am unsure how to access the response data. If I use console.log() to view the response I get this:

Observable { _subscribe: [Function (anonymous)] }

I'm new to both Nest.js and the concept of an Observable. I would be grateful for an example to make a HTTP request and access the response data.

Obvious_Grapefruit
  • 640
  • 1
  • 8
  • 21

2 Answers2

42

If you want to make the HttpService use a promise instead of on RxJS Observable you can use lastValueFrom wrapping around the this.httpService.post() call. This will transform the Observable into a promise and you can await it as normal. Otherwise, if you just return the observable, Nest will handle waiting for the response for you. Either way, you'll need to make sure to use that map((resp) => resp.data) function you have so you don't end up with circular data in the response object (as Axios's response object is circular by design).

If you're trying to console.log() the data, you'll want to use tap along with map in the form of

this.httpService.post(url, data, options).pipe(
  tap((resp) => console.log(resp)),
  map((resp) => resp.data),
  tap((data) =>  console.log(data)),
);

tap is essentially a spy method to tap into the observable, look at the data, and let it pass through. It can mutate the data, but generally it's a good idea to leave that to map or other rxjs operators.


For just the simple await ability, something like this is all that's needed

const data = await lastValueFrom(
  this.httpService.post(url, data, options).pipe(
    map(resp => res.data)
  )
);

Example with AxiosRequestConfig object type (TypeScript)

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;
    }),
  ),
);
Matthew Rideout
  • 7,330
  • 2
  • 42
  • 61
Jay McDoniel
  • 57,339
  • 7
  • 135
  • 147
1

AxiosResponse should be imported from axios:

import { AxiosResponse } from 'axios'

You can make use of import suggestions by pressing ctrl+space (or options + esc on mac) or by using ctrl+.