programing

Google reCaptcha 응답 "미포착(약속) null"

sourcejob 2023. 1. 27. 21:19
반응형

Google reCaptcha 응답 "미포착(약속) null"

reCaptcha v2를 사용하지만 개발 콘솔 응답에 있음Uncaught (in promise) null어떤 경우에도 (및 이동).reset()기능)

콘솔:

여기에 이미지 설명 입력

탈환용 내 코드:

<div class="text-xs-center" style="text-align: center; height:150px;">
    <p style="color: black;"> Complete the verification: </p>
    <div style="display: inline-block;" class="g-recaptcha" data-sitekey="xxxxxxxxxxx" data-callback="callback"></div>
</div>

콜백 기능:

function callback() {
    if (grecaptcha === undefined) {
        alert('Recaptcha non definito'); 
        return; 
    }

    var response = grecaptcha.getResponse();
    console.log(response);

    if (!response) {
        alert('Coud not get recaptcha response'); 
        return; 
    }

    $.ajax({
    'url' : 'validate-recaptcha.php',
    'type' : 'POST',
    'data' : {
        'response' : response   
    },
    'success' : function(data) {              
        alert('Data: '+data);
    },
    'error' : function(request,error)
    {
        alert("Request: "+JSON.stringify(request));
    }
    });
    grecaptcha.reset();
}

그리고 내 인증도 받았지php:

<?php
//debug
$fp = fopen('debug.txt', 'a');
fwrite($fp, print_r($_POST, TRUE));
fclose($fp);
//enddebug

if (empty($_POST['recaptcha'])) {
    exit('Please set recaptcha variable');
}
// validate recaptcha
$response = $_POST['recaptcha'];
$post = http_build_query(
    array (
        'response' => $response,
        'secret' => 'yoursecretkey',
        'remoteip' => $_SERVER['REMOTE_ADDR']
    )
);
$opts = array('http' => 
    array (
        'method' => 'POST',
        'header' => 'application/x-www-form-urlencoded',
        'content' => $post
    )
);
$context = stream_context_create($opts);
$serverResponse = @file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);
if (!$serverResponse) {
    exit('Failed to validate Recaptcha');
}
$result = json_decode($serverResponse);
if (!$result -> success) {
    exit('Invalid Recaptcha');
}
exit('Recaptcha Validated');

인터넷 검색의 경우, 아마도 문제는.reset()기능을 합니다만, 솔루션을 이해할 수 없습니다.

Google retracha/admin 도메인 영역에서 사이트가 "등록"되지 않은 경우에도 이 문제가 발생하는 것으로 나타났습니다.

솔루션:retapcha 관리 영역에 도메인을 추가합니다.

  1. retailcha 키가 등록된 Google 계정에 로그인합니다.
  2. Google "Google recpatcha 관리 콘솔"에 입력합니다.
  3. (프로덕션) 키의 설정으로 이동합니다.
  4. "도메인"에서 다음 두 항목을 추가합니다.
localhost
127.0.0.1
  1. 저장하고 탈환을 테스트합니다.

개발 키에서 프로덕션 키로 전환할 때 이 오류가 발생했습니다.프로덕션 키에 localhost에 대한 항목이 없습니다.

프록시 리다이렉트 뒤에 위치하도록 API 응답을 설정했습니다.따라서 Google Admin 콘솔에서 구성되지 않은 로컬 호스트 환경에서 확인 작업이 수행되었으며, 이로 인해 이 일반 오류가 발생했습니다.

그의 코멘트에서 그것을 지적한 @Christian Zagarskas의 공로를 인정합니다.

Recapcha v2 콜백 js 오류

저도 이 오류가 발생했는데 retailcha callback(고객님의 경우)과 관련이 있음을 알게 되었습니다.data-callback="callback"data-callback Atribute를 삭제해도 에러는 발생하지 않습니다.

콘솔 오류Uncaught (in promise) null콜백이 약속을 기다리고 있음을 나타냅니다.다음은 약속을 사용한 탈환에 대한 기본 콜백 함수입니다.

function callback() {
    return new Promise(function(resolve, reject) { 

    //Your code logic goes here

    //Instead of using 'return false', use reject()
    //Instead of using 'return' / 'return true', use resolve()
    resolve();

  }); //end promise
};

이 경우 코드를 다음과 같이 조정해야 합니다.

function callback() {
  return new Promise(function(resolve, reject) {  

    if (grecaptcha === undefined) {
        alert('Recaptcha non definito'); 
        //return;
        reject();
    }

    var response = grecaptcha.getResponse();
    console.log(response);

    if (!response) {
        alert('Coud not get recaptcha response'); 
        //return;
        reject();
    }

    $.ajax({
    'url' : 'validate-recaptcha.php',
    'type' : 'POST',
    'data' : {
        'response' : response   
    },
    'success' : function(data) {              
        alert('Data: '+data);
        resolve();
    },
    'error' : function(request,error)
    {
        alert("Request: "+JSON.stringify(request));
        reject();   
    }
    });
    grecaptcha.reset();

  }); //end promise
}

SO에 대한 첫 회답이니 조금만 기다려 주시고, 혹시 잊어버리거나 빠뜨린 것이 있으면 가르쳐 주세요.

이 에러의 또 다른 원인은, 「submit」라고 하는 이름의 어트리뷰트를 가지는 버튼입니다.reCaptcha 문서의 자동 바인딩 예제 코드를 사용하면 'form.submit'은 폼 자체의 submit() 함수가 아닌 버튼을 참조하기 때문에 이 코드가 트립됩니다.도!

<html>
  <head>
    <title>reCAPTCHA demo: Simple page</title>
     <script src="https://www.google.com/recaptcha/api.js" async defer></script>
     <script>
       function onSubmit(token) {
         document.getElementById("demo-form").submit();
       }
     </script>
  </head>
  <body>
    <form id='demo-form' action="?" method="POST">
      <!-- Oops.... avoid the name="submit" below -->
      <button name="submit" class="g-recaptcha" data-sitekey="your_site_key" data-callback='onSubmit'>Submit</button>
      <br/>
    </form>
  </body>
</html>

이 문제는 콜백코드로 인해 오류가 발생했을 때 발생할 수 있습니다.제 경우 콜백이 존재하지 않는 변수를 참조했을 뿐이고, 같은 에러가 발생했습니다.그렇게 간단한 것치고는 아주 이상한 오류야!

도 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★. 에러는 로, 이 에러는 에러를 의미하는 것 .fix the code in your callback!.

여기에 제 구체적인 경험으로 답변을 추가해야 할 것 같습니다.가장 높은 답변에 신뢰를 보냅니다. 제 답변의 일부가 될 것입니다.

다음 정보를 얻을 수 있었습니다.Uncaught (in promise) null콘솔에서 오류를 확장해 보니 비어 있었습니다.

이 코드로부터 코드를 변경했습니다.

function onSubmit(token) {
    if (grecaptcha.getResponse() !== "") {
        $('#request-form').submit();
    }
    grecaptcha.reset();
}

이를 위해:

function onSubmit(token) {
    return new Promise(function (resolve, reject) {

        if (grecaptcha.getResponse() !== "") {
            $('#request-form').submit();
        }
        grecaptcha.reset();

    });
}

이 변경으로 콘솔에 특정 오류 메시지가 나타납니다.그런 다음 특정 문제를 해결할 수 있습니다.

John Rix의 문제/솔루션과 유사합니다.제출 요소의 ID가 'submit'인 경우에도 오류가 발생했습니다.

<!-- Avoid id="submit" below -->
<input type="submit" id="submit" value="submit">```

에는 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★.jquery.3.4.1.slim.js 나는 리리 to to to to to to to to to to to to로 바꿨다로 .jquery.3.4.1.min.js오류가 사라졌습니다.는 ★★★★★★★★★★★★★★★★★★★★에 있다.ASP.NET WebForms.

이런 문제가 있었어요.콜백 함수에 jquery 코드가 있고 어떤 이유로 jquery 스크립트를 포함시키는 것을 잊어버렸기 때문입니다.따라서 이 문제가 있는 경우 콜백 코드의 각 행을 주의 깊게 살펴보시기 바랍니다.한 줄 한 줄 복잡함을 줄이면 해결책을 얻을 수 있습니다.오류 처리는 더 나은 방법으로 수행되어야 합니다.

ASP の asp asp 。3.에서는 이 하여 NET Core 3.1 Identity를 했습니다.jquery.validate.min.js ★★★★★★★★★★★★★★★★★」jquery.validate.unobtrusive.min.js의 최신 합니다._ValidationScriptsPartial.cshtml.

같은 문제가 발생했는데 localhost를 지원되는 도메인 목록에 추가하지 않은 것이 문제였습니다.

이 오류가 발생한 이유는 다음과 같습니다.

const onChange = e => {
  e.preventDefault();
  console.log('success')
}

<ReCAPTCHA sitekey="yeet" onChange={onChange} />

「」의 삭제"e.preventDefault()에러를 삭제.

언급URL : https://stackoverflow.com/questions/52390562/google-recaptcha-response-uncaught-in-promise-null

반응형