Javascript 谷歌 reCaptcha 响应“未捕获(承诺)空”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/52390562/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Google reCaptcha response "Uncaught (in promise) null"
提问by FABBRj
I'm use reCaptcha v2 but in dev console response Uncaught (in promise) nullin in any case (and moving the .reset()function) 
我正在使用 reCaptcha v2,但在Uncaught (in promise) null任何情况下都在开发控制台响应中(并移动.reset()功能)
console:
安慰:
my code for recaptcha:
我的 recaptcha 代码:
<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>
my callback function:
我的回调函数:
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();
}
and my validate-recaptcha.php:
和我的validate-recaptcha.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');
Searching on the internet, probably the problem is the .reset()function, but I do not understand the solution.
在网上查了一下,可能是.reset()功能的问题,但我不明白解决方案。
采纳答案by EsaulFarfan


I had this error too and I found is related with the recaptcha callback (in your case data-callback="callback"). If you remove your data-callback attribute the error won't come up.
我也有这个错误,我发现与 recaptcha 回调有关(在你的情况下data-callback="callback")。如果您删除 data-callback 属性,则不会出现错误。
The console error Uncaught (in promise) nullindicates the callback is waiting for a promise. Here's a basic callback function for recaptcha using promises:
控制台错误Uncaught (in promise) null表明回调正在等待承诺。这是使用 promise 的 recaptcha 的基本回调函数:
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
};
In your case you need to adjust your code to something like this:
在您的情况下,您需要将代码调整为如下所示:
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
}
This is my first answer in SO, so please be patient and let me know if I forgot or missed something :)
这是我在 SO 中的第一个答案,所以请耐心等待,如果我忘记或错过了什么,请告诉我:)
回答by EliteRaceElephant
Turns out it also occurs when a site is not "registered" in the Google recaptcha/admin Domains area.
事实证明,当站点未在 Google recaptcha/admin Domains 区域中“注册”时,也会发生这种情况。
Solution: Add the domain in the recaptcha admin area:
解决方法:在recaptcha管理区添加域:
- Sign into your Google account where your recaptcha keys are registered
- Type into Google "google recpatcha admin console"
- Go to your settings for your (production) key
- In "Domains", add these two entries:
- 登录到您注册了重新验证码的 Google 帐户
- 输入谷歌“google recpatcha 管理控制台”
- 转到(生产)密钥的设置
- 在“域”中,添加以下两个条目:
localhost 127.0.0.1
localhost 127.0.0.1
- Save it and test your recaptcha.
- 保存并测试您的验证码。
I made this error when I switched from a development key to a production key. The production key did not have any entries for localhost.
当我从开发密钥切换到生产密钥时,我犯了这个错误。生产密钥没有 localhost 的任何条目。
I configured the API response to sit behind a proxy-redirect. Therefore the verification was working in a localhost environment which was not configured in the Google Admin console which caused this generic error.
我将 API 响应配置为位于代理重定向之后。因此,验证是在 localhost 环境中进行的,该环境未在导致此一般错误的 Google 管理控制台中进行配置。
Credit to @Christian ?agarskas who pointed it out in his comment.
感谢@Christian ?agarskas,他在评论中指出了这一点。
回答by John Rix
Another trigger for this error that plagued me was having a button in the form with a name attribute of 'submit'. If using the automatic binding example code from the reCaptcha documentation, this will trip it up, since 'form.submit' will refer to the button rather than the submit() function of the form itself. Doh!
这个困扰我的错误的另一个触发因素是表单中有一个名称属性为“提交”的按钮。如果使用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>
回答by Trev14
In my case, my callback just referenced some variable that didn't exist and I saw the same error. Very weird error for something so simple!
就我而言,我的回调只是引用了一些不存在的变量,我看到了同样的错误。对于如此简单的事情,非常奇怪的错误!
I also saw the same error when I left a .after a variable name on accident. Seems like this is a super generic error that means fix the code in your callback!.
当我.意外地在变量名之后留下 a 时,我也看到了同样的错误。似乎这是一个超级通用的错误,意味着fix the code in your callback!.
回答by CrazyPaste
I feel I should add an answer here with my specific experience. I give credit to the top answer, which will be part of my answer.
我觉得我应该根据我的具体经验在这里添加一个答案。我相信最高答案,这将成为我答案的一部分。
I was getting: Uncaught (in promise) null.  When I expanded the error in the console it was empty.
我得到:Uncaught (in promise) null。当我在控制台中展开错误时,它是空的。
I changed my code from this:
我从这个改变了我的代码:
function onSubmit(token) {
    if (grecaptcha.getResponse() !== "") {
        $('#request-form').submit();
    }
    grecaptcha.reset();
}
To this:
对此:
function onSubmit(token) {
    return new Promise(function (resolve, reject) {
        if (grecaptcha.getResponse() !== "") {
            $('#request-form').submit();
        }
        grecaptcha.reset();
    });
}
What this change does is allows you to receive a specific error message in your console. You can then proceed to fix your specific problem.
此更改的作用是允许您在控制台中接收特定的错误消息。然后,您可以继续解决您的特定问题。
回答by Santiago quits SO
In my case I was using jquery.3.4.1.slim.jsthen I changed to jquery.3.4.1.min.jsand the error disappeared. I'm on ASP.NET WebForms.
在我的情况下,我正在使用jquery.3.4.1.slim.js然后我改为jquery.3.4.1.min.js并且错误消失了。我在ASP.NET WebForms。
回答by epluribusunum
Similar to John Rix issue/solution. I also got the error when the id of the submit element was 'submit'.
类似于 John Rix 问题/解决方案。当提交元素的 id 为“提交”时,我也收到了错误消息。
<!-- Avoid id="submit" below -->
<input type="submit" id="submit" value="submit">```
回答by Prashant Onkar
I had this issue. It was because in my callback function jquery code was there and for some reason, I had forgotten to include the jquery script. So if you are having this issue, I suggest you to carefully go through each line of your call back code. May be reduce the complexity line by line and you will get the solution. The error handling should have been done in a better way.
我有这个问题。这是因为在我的回调函数中存在 jquery 代码,并且出于某种原因,我忘记了包含 jquery 脚本。因此,如果您遇到此问题,我建议您仔细检查回调代码的每一行。可能会逐行降低复杂性,您将获得解决方案。错误处理应该以更好的方式完成。

