Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

nestjs

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

This is my code:

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

    return this.httpService.post('<url of rest endpoint to verify captcha>', {
        captcha_response
    });
}

However, Visual Studio Code says Cannot find name 'AxiosResponse'. Where can I import this from? This type was used in the Nest.js docs as Observable<AxiosResponse<Cat[]>>. I decided to remove this and just use the type Observable<any>.

This works. However, if I use console.log() to view the response I get this:

Observable { _subscribe: [Function (anonymous)] }

Most answers I found on StackOverflow suggest to use some variation of this:

return this.httpService.post('<url of rest endpoint to verify captcha>', {
        captcha_response
    }).pipe(map(response => response.data));

...but console.log() gives me this:

Observable {
  source: Observable { _subscribe: [Function (anonymous)] },
  operator: [Function (anonymous)]
}

Some other answers on StackOverflow suggest to use .toPromise(), but apparently this is deprecated.

All in all, I'm new to Nest.js and I'm super confused. Since I can't find one, I would be really grateful for a complete and up-to-date example of how to make a simple POST request and return the response as JSON.

like image 332
Obvious_Grapefruit Avatar asked Sep 11 '21 04:09

Obvious_Grapefruit


People also ask

Can I use Axios in NestJS?

Axios is richly featured HTTP client package that is widely used. Nest wraps Axios and exposes it via the built-in HttpModule . The HttpModule exports the HttpService class, which exposes Axios-based methods to perform HTTP requests.

How does NestJS call external API?

I believe what you need to do is create a Service, put your example code into a function, then call that function from a controller or resolver with DI to the Service you just created. please see sample code below for your reference. can also use HttpModule instead of raw axios as per the nestjs documentation.

How do you send a body request in Axios?

To perform an HTTP POST request in Axios, call axios. post() . Making a POST request in Axios requires two parameters: the URI of the service endpoint and an object that contains the properties you wish to send to the server. For a simple Axios POST request, the object must have a url property.

Is NestJS open source?

NestJS is an open-source, extensible, versatile, progressive Node. Js framework for creating compelling and demanding backend systems. It's currently the fastest-growing Node. Js framework in TypeScript.


2 Answers

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;
    }),
  ),
);
like image 111
Jay McDoniel Avatar answered Dec 31 '22 08:12

Jay McDoniel


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

like image 44
PYTHON DEVELOPER999 Avatar answered Dec 31 '22 09:12

PYTHON DEVELOPER999