0
votes

I have made a new angular app and I have tried to integrate recaptcha v2 with it.

I am able to get the response from re-captcha after parsing my siteKey.

And I did a manual post request to google recaptcha api with my response and secret key, and it indeed returns the result I need, the success status of true/false.

Next, I tried to do a http however it began returning me the following error:

Access to XMLHttpRequest at 'https://www.google.com/recaptcha/api/siteverify' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I have tried adding a proxy conf to my angular, however it does not work. And I did the same application on PHP and it works. May I know if there's any solution to this?

The following are my codes in angular

my-form.component.html

<div class="recaptcha">
    <re-captcha (resolved)="resolved($event)" siteKey="6LeD_K8ZAAAAAOAGZHqFwujgLXqLrTIoftoPzXWb"></re-captcha>
</div>

my-form.component.ts

import { Component, OnInit } from '@angular/core';

//My Imports
import { HttpClient, HttpParams } from '@angular/common/http';

@Component({
  selector: 'app-my-form',
  templateUrl: './my-form.component.html',
  styleUrls: ['./my-form.component.css']
})
export class MyFormComponent implements OnInit 
{
  constructor(private http: HttpClient) { }

  resolved(captchaResponse: string)
  {
    if(captchaResponse != null)
    {
      let params = new HttpParams()
      .set("secret", "i459wfj3n42rls939jfi3j9-")
      .set("response", captchaResponse);
      
      //THE ERROR OCCURS WHEN I POST.
      this.http.post("https://www.google.com/recaptcha/api/siteverify", { params })
      .subscribe((value:any)=> 
      {
        console.log(value);
      })
    }

  }

  ngOnInit(): void {
  }

}

src/proxy.conf.json

{
  "/api/*": {
      "target": "http://localhost:3000",
      "secure": false,
      "logLevel": "debug"
  }
}

angular.json

    "serve": {
      "builder": "@angular-devkit/build-angular:dev-server",
      "options": {
        "browserTarget": "googlerecaptcha:build",
        "proxyConfig": "src/proxy.conf.json"
1

1 Answers

0
votes

You can use a thrid part dependancy : https://github.com/JamesHenry/angular-google-recaptcha

Or you can add the js script in your angular application : https://w3path.com/how-to-integrate-recaptcha-in-angular-8/

You can't use proxy for that.

(My first anwser was wrong, so i updated it)