Obvious_Grapefruit
Obvious_Grapefruit

Reputation: 870

How to use axios HttpService from Nest.js to make a POST request

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.

Upvotes: 31

Views: 82358

Answers (4)

Ashish Kumar
Ashish Kumar

Reputation: 230

You can access the response data from the Observable returned by httpService.post by subscribing to it. Here's how you can modify your code to do so:

verifyResponse(captcha_response: string): Observable<any> {
  return this.httpService.post('some url', { captcha_response }).pipe(
    map(response => response.data)
  );
}

And when you call verifyResponse, you can subscribe to it and handle the response data accordingly:

verifyResponse(captcha_response: string): void {
  this.verifyResponse(captcha_response).subscribe(
    data => {
        // Handle the response data here
        console.log(data);
    },
    error => {
        // Handle errors if any
        console.error(error);
    }
  );
}

This way, you'll be able to access the response data and handle it appropriately without needing to modify the returned Observable.

Additionally, if you'd like to explore more about handling HTTP requests in Nest.js with Axios, you might find this post helpful.

Upvotes: 1

Maksim Khitrov
Maksim Khitrov

Reputation: 9

Exampe with 'axiosRef.request':

const config: AxiosRequestConfig = {
  url,
  method,
  params,
  headers,
  data,
};

try {
  const response = await this.httpService.axiosRef.request(config);
  return response.data;
} catch (error) {
  console.log(error);
}

Exampe with 'axiosRef.post':

try {
  const url = `some url`;
  const data = {};
  return await this.httpService.axiosRef.post(url, data);
} catch (error) {
  console.log(error);
}

Upvotes: 0

Jay McDoniel
Jay McDoniel

Reputation: 70131

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;
    }),
  ),
);

Upvotes: 49

PYTHON DEVELOPER999
PYTHON DEVELOPER999

Reputation: 331

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+.

Upvotes: 1

Related Questions