Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将reCAPTCHA与Angular 4集成的正确方法_Angular_Recaptcha_Angular4 Forms_Angular Forms_Invisible Recaptcha - Fatal编程技术网

将reCAPTCHA与Angular 4集成的正确方法

将reCAPTCHA与Angular 4集成的正确方法,angular,recaptcha,angular4-forms,angular-forms,invisible-recaptcha,Angular,Recaptcha,Angular4 Forms,Angular Forms,Invisible Recaptcha,我想把A和我的角4形式结合起来 在组件的TS部分,我有如下功能: onSubmit(token: string) { alert(token); } 我的HTML如下所示(仅显示相关部分): 提交 当点击该按钮时,我会收到一条警告,说令牌未定义,或者我会收到一条错误消息,如:“无法联系reCAPTCHA。请检查您的连接并重试。”不是真正确定的-有时我会看到一种行为,有时会看到另一种行为 我认为表单标记中的(ngSubmit)可能会干扰reCAPTCHA。但是如果我删除(ngSubm

我想把A和我的角4形式结合起来

在组件的TS部分,我有如下功能:

onSubmit(token: string) {
    alert(token);
}
我的HTML如下所示(仅显示相关部分):


提交
当点击该按钮时,我会收到一条警告,说令牌未定义,或者我会收到一条错误消息,如:“无法联系reCAPTCHA。请检查您的连接并重试。”不是真正确定的-有时我会看到一种行为,有时会看到另一种行为

我认为表单标记中的
(ngSubmit)
可能会干扰reCAPTCHA。但是如果我删除
(ngSubmit)
,那么根本不会调用
onSubmit
函数

集成此功能的正确方法是什么

AngularJS也有一个类似的问题,但我真的不知道如何使该解决方案适应Angular4。

在component.html中:

<re-captcha (resolved)="resolved($event)" siteKey="enter key"></re-captcha>
首先在模块中加载此文件

import { RecaptchaModule } from 'ng-recaptcha';
imports: [
    BrowserModule,
     RecaptchaModule.forRoot(),  
    // RecaptchaFormsModule,  
] 
在index.html中 装载


ReCAPTCHA可按如下方式以角度实施。请注意,此示例不包括所需的服务器端代码

先决条件 包括

但是,为了获得更多的类型支持,可以使用接口
ReCAPTCHA

declare var grecaptcha: ReCAPTCHA;
ReCAPTCHA接口(v2)[ReCAPTCHA.ts]

ReCAPTCHA角度服务[ReCAPTCHA.Service.ts] 组件模板
这是我目前在Angular 10中使用的一个很好的reCAPTCHA npm库

npm i ng-recaptcha

看起来很有趣。我稍后会试试。谢谢你的提示!这可能会对您有所帮助:验证码响应似乎是加密的。你知道我们如何解密它吗?这是非常有用的,我已经设法使所有不同的位工作,除了我得到错误“缺少输入响应”。我没有使用“隐形”选项。这需要一个不同的实现吗?好的,对于其他有这个问题的人来说,这与后端(服务器端)请求有关。显然,谷歌希望URL如下:
https://www.google.com/recaptcha/api/siteverify?secret=“+secret+”&response=“+responseToken
。除此之外,如果您不想安装npm包或编写指令,这是一个很好的答案,而且非常简单。
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
declare var grecaptcha: any;
declare var grecaptcha: ReCAPTCHA;
import { ElementRef } from '@angular/core';

/**
 * Interface for Google's reCAPTCHA JavaScript API. 
 * 
 * Display API
 * @see {@link https://developers.google.com/recaptcha/docs/display}
 * 
 * Invisible API
 * @see {@link https://developers.google.com/recaptcha/docs/invisible}
 */
export interface ReCAPTCHA {

  /**
   * Programatically invoke the reCAPTCHA check. Used if the invisible reCAPTCHA is on a div 
   * instead of a button.
   * 
   * @param {string} opt_widget_id Optional widget ID, defaults to the first widget created if 
   *     unspecified.
   */
  execute(opt_widget_id?: string): void;

  /** 
   * Renders the container as a reCAPTCHA widget and returns the ID of the newly created widget.
   * 
   * @param {ElementRef|string} container The HTML element to render the reCAPTCHA widget.  Specify 
   *    either the ID of the container (string) or the DOM element itself. 
   * @param {Object} parameters An object containing parameters as key=value pairs, for example,
   *    {"sitekey": "your_site_key", "theme": "light"}.
   */
  render(container: ElementRef|string, parameters: {[key: string]: string}): void;

  /** 
   * Resets the reCAPTCHA widget.
   * 
   * @param {string} opt_widget_id Optional widget ID, defaults to the first widget created if 
   *     unspecified.
   */
  reset(opt_widget_id?: string): void;

  /** 
   * Gets the response for the reCAPTCHA widget. Returns a null if reCaptcha is not validated. 
   * 
   * @param {string} opt_widget_id Optional widget ID, defaults to the first widget created if 
   *     unspecified.
   */
  getResponse(opt_widget_id?: string): string;
}
import { Injectable, OnInit } from '@angular/core'
import { HttpClient, HttpErrorResponse, HttpHeaders, HttpParams, HttpResponse } from '@angular/common/http'
import { Observable } from 'rxjs'
import { map } from 'rxjs/operators'

export interface ReCAPTCHAResponse {
  success: boolean; 
  status_code: number,
  error_codes?: Array<string>;
}

const httpOptions = {
  headers: {'Content-Type': 'application/json'},
  observe: "body",
  responseType: "json",
  withCredentials: true
}


@Injectable()
export class ReCAPTCHAService {
  public constructor(private http: HttpClient) {}

  public verifyUserResponse(userResponseToken: string): Observable<ReCAPTCHAResponse> {
    return this.http.post<ReCAPTCHAResponse>('/auth/captcha', {'g-recaptcha-response': userResponseToken}, httpOptions).
      pipe(map( (resp: HttpResponse) => { ... resp.body }))
  } 
}
import { Component, OnDestroy, OnInit } from '@angular/core'
import { ReCAPTCHA } from './recaptcha'
import { ReCAPTCHAResponse, ReCAPTCHAService } from './recaptcha.service'


declare var grecaptcha: ReCAPTCHA;
declare var window: any;

@Component ({
  moduleId: module.id,
  selector: 'create-account',
  templateUrl: 'create-account.component.html'
})
export class CreateAccountComponent implements OnDestroy, OnInit {

  public constructor(private recaptcha: ReCAPTCHAService) {}

  public ngOnInit(): void {
    // Export reCAPTCHACallback to global scope.
    window['reCAPTCHACallback'] = this.reCAPTCHACallback.bind(this);

    grecaptcha.render('create-account-captcha', {
      'sitekey': 'your-site-key',
      'size': 'invisible',        // Optional (see docs)
      'callback': 'reCAPTCHACallback'
    });
  }

  /**
   * Verify reCAPTCHA response on server. 
   */
  public reCAPTCHACallback(token: string) {
    if (token == null || token.length === 0) {
      grecaptcha.reset();
      // TODO: report that captcha was invalid
    } else {
      this.recaptcha.verifyUserResponse(token).subscribe(
        (r: ReCAPTCHAResponse) => {
          if (r.success) {
            // TODO: create the new user account
          } else {
            grecaptcha.reset();
            // TODO: report that captcha was invalid
          }
        },
        (error: any) => {
          // TODO: handle server error
        }
      })
  }
}
<!-- Invisible reCAPTCHA dynamically rendered. -->
<div id='create-account-captcha' class="g-recaptcha"></div>
npm i ng-recaptcha