1

I used the following code in order to get the response from the request, but I got an special result that I don't know:

import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';

@Injectable()
export class RecaptchaService {
  constructor(private httpService: HttpService) {}
  verifyResponse(reCAPTCHAToken: string, clientIp: string): number {
    const checkResult = this.httpService.post(
      'https://www.recaptcha.net/recaptcha/api/siteverify',
      {
        secret: 'AAAA',
        response: reCAPTCHAToken,
        remote: clientIp,
      },
    );
    console.log(checkResult);
    return 0.2;
  }
}

The result:

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

Additionally, I tried the methods in This Answer but still get the same result

Aurora
  • 47
  • 1
  • 9

2 Answers2

1

It returns an observable, see: https://rxjs.dev/guide/observable, so you need to handle it like that:

checkResult.subscribe(value => console.log(value))

or convert it to promise:

const result = await checkResult.toPromise()
Naor Levi
  • 1,713
  • 1
  • 13
  • 27
  • Thanks, I can get response at console now, but how can I get it outside the callback of subcribe so that I can do more on it – Aurora Jun 07 '22 at 05:03
  • This is becoming an attitude, read about Observables in the link I posted in the answer. But to simplify, call your own function at `subscribe` callback, or either you the 2nd option as converting to a promise. – Naor Levi Jun 07 '22 at 07:17
0

The Axios packaged by Nestjs will return an Observables object. After consulting the Rxjs documentation, the following code is used to effectively solve the problems and requirements:

import { Injectable } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { lastValueFrom } from 'rxjs';

type VerifyResponse = (
  reCAPTCHAToken: string,
  clientIp: string,
) => Promise<number | boolean>;

@Injectable()
export class RecaptchaService {
  constructor(private httpService: HttpService) {}
  verifyResponse: VerifyResponse = async (reCAPTCHAToken, clientIp) => {
    const checkResultObservable = this.httpService.post(
      'https://www.recaptcha.net/recaptcha/api/siteverify',
      {
        secret: 'AAAA',
        response: reCAPTCHAToken,
        remote: clientIp,
      },
    );
    const checkResult = await (await lastValueFrom(checkResultObservable)).data;
    console.log(checkResult);
    return 0.2;
  };
}
Aurora
  • 47
  • 1
  • 9
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 07 '22 at 12:08