Skip to content

验证验证码

服务器端点 可用作 REST API 端点来运行身份验证、数据库访问和验证等功能,而无需向客户端暴露敏感数据。

¥Server endpoints can be used as REST API endpoints to run functions such as authentications, database access, and verifications without exposing sensitive data to the client.

在本秘籍中,API 路由用于验证 Google reCAPTCHA v3,而不会将秘密暴露给客户端。

¥In this recipe, an API route is used to verify Google reCAPTCHA v3 without exposing the secret to clients.

¥Prerequisites

  • 启用了 SSR (output: 'server') 的项目

¥Recipe

  1. Create a POST endpoint that accepts recaptcha data, then verifies it with reCAPTCHA’s API. Here, you can safely define secret values or read environment variables.

    src/pages/recaptcha.js
    export async function POST({ request }) {
    const data = await request.json();
    const recaptchaURL = 'https://www.google.com/recaptcha/api/siteverify';
    const requestHeaders = {
    'Content-Type': 'application/x-www-form-urlencoded'
    };
    const requestBody = new URLSearchParams({
    secret: "YOUR_SITE_SECRET_KEY", // This can be an environment variable
    response: data.recaptcha // The token passed in from the client
    });
    const response = await fetch(recaptchaURL, {
    method: "POST",
    headers: requestHeaders,
    body: requestBody.toString()
    });
    const responseData = await response.json();
    return new Response(JSON.stringify(responseData), { status: 200 });
    }
  2. Access your endpoint using fetch from a client script:

    src/pages/index.astro
    <html>
    <head>
    <script is:inline src="https://www.google.com/recaptcha/api.js"></script>
    </head>
    <body>
    <button class="g-recaptcha"
    data-sitekey="PUBLIC_SITE_KEY"
    data-callback="onSubmit"
    data-action="submit"> Click me to verify the captcha challenge! </button>
    <script is:inline>
    function onSubmit(token) {
    fetch("/recaptcha", {
    method: "POST",
    body: JSON.stringify({ recaptcha: token })
    })
    .then((response) => response.json())
    .then((gResponse) => {
    if (gResponse.success) {
    // Captcha verification was a success
    } else {
    // Captcha verification failed
    }
    })
    }
    </script>
    </body>
    </html>
Astro 中文网 - 粤ICP备13048890号