Google reCAPTCHA API间歇性返回404错误问题求助
问题根因
该间歇性404错误的核心原因是Google reCAPTCHA的API加载过程中未正确获取到版本哈希标识:正常请求路径中/releases/后携带的随机字符串为资源版本号,加载失败时该版本号为空,导致路径出现//的非法格式,请求404。
修复方案
- 方案1:指定稳定版本加载
在引入API的URL后追加v=stable参数,强制拉取稳定版资源,避免动态获取版本号失败的问题,修改后的引入代码如下:<script src="https://www.google.com/recaptcha/api.js?onload=aminvisiblecaptchaOnloadCallback&render=explicit&v=stable" async defer></script> - 方案2:添加错误重试逻辑
监听脚本加载错误事件,出现异常时自动重试,避免单次网络波动导致加载失败,示例代码如下:let retryTimes = 0; const MAX_RETRY_COUNT = 3; function initRecaptcha() { const script = document.createElement('script'); script.src = 'https://www.google.com/recaptcha/api.js?onload=aminvisiblecaptchaOnloadCallback&render=explicit'; script.async = true; script.defer = true; script.onerror = () => { if(retryTimes < MAX_RETRY_COUNT) { retryTimes++; document.head.removeChild(script); setTimeout(initRecaptcha, 1000); } } document.head.appendChild(script); } window.addEventListener('load', initRecaptcha); - 方案3:替换更稳定的API域名
如果是国内访问场景,可将域名替换为reCAPTCHA官方中国镜像域名www.recaptcha.net,访问稳定性更高,修改后的引入地址如下:<script src="https://www.recaptcha.net/recaptcha/api.js?onload=aminvisiblecaptchaOnloadCallback&render=explicit" async defer></script>
内容的提问来源于stack exchange,提问作者Willian Melo
相关产品推荐
相关产品推荐

