You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无后端支持能否使用Google reCAPTCHA?Nuxtjs 2客户端实现方法

Nuxt.js 2 前端实现 Google reCAPTCHA 验证(无后端依赖)

以下提供两种实现方案,均无需后端支持,仅通过前端完成基础的人机校验:

方案一:使用兼容的第三方库(vue-recaptcha)

vue-recaptcha 是适配 Vue 2 的 reCAPTCHA 组件库,能快速集成到 Nuxt.js 2 项目中。

步骤1:安装依赖

npm install vue-recaptcha
# 或
yarn add vue-recaptcha

步骤2:配置 Nuxt 插件

在项目根目录创建 plugins/vue-recaptcha.js 文件,注册组件:

import Vue from 'vue'
import VueRecaptcha from 'vue-recaptcha'

Vue.component('vue-recaptcha', VueRecaptcha)

修改 nuxt.config.js,将插件设置为仅客户端加载:

export default {
  plugins: [
    { src: '~/plugins/vue-recaptcha.js', mode: 'client' }
  ]
}

步骤3:在页面/组件中使用

由于 reCAPTCHA 依赖浏览器环境,需用 <client-only> 包裹组件:

<template>
  <client-only>
    <vue-recaptcha
      ref="recaptcha"
      sitekey="你的Google reCAPTCHA站点密钥"
      @verify="handleVerify"
      @expired="handleExpired"
    ></vue-recaptcha>
    <button @click="submitForm">提交</button>
  </client-only>
</template>

<script>
export default {
  data() {
    return {
      recaptchaToken: null
    }
  },
  methods: {
    handleVerify(token) {
      this.recaptchaToken = token
      console.log('reCAPTCHA验证成功,token:', token)
    },
    handleExpired() {
      this.recaptchaToken = null
      console.log('reCAPTCHA验证已过期,请重新验证')
    },
    submitForm() {
      if (!this.recaptchaToken) {
        alert('请先完成reCAPTCHA人机验证')
        return
      }
      // 这里可执行前端提交逻辑,比如将token附带发送到允许前端调用的第三方接口
      console.log('准备提交,携带token:', this.recaptchaToken)
    }
  }
}
</script>

方案二:原生实现(不依赖第三方库)

直接引入 Google reCAPTCHA 官方脚本,手动处理验证逻辑。

步骤1:引入官方脚本

修改 nuxt.config.js,在 head 中添加 reCAPTCHA 脚本(仅客户端加载):

export default {
  head: {
    script: [
      {
        src: 'https://www.google.com/recaptcha/api.js',
        async: true,
        defer: true,
        mode: 'client'
      }
    ]
  }
}

步骤2:在页面/组件中实现验证

<template>
  <div>
    <div 
      class="g-recaptcha" 
      :data-sitekey="siteKey" 
      data-callback="handleRecaptchaVerify"
    ></div>
    <button @click="submitForm">提交</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      siteKey: '你的Google reCAPTCHA站点密钥',
      recaptchaToken: null
    }
  },
  mounted() {
    // 注册全局回调函数,供reCAPTCHA脚本调用
    window.handleRecaptchaVerify = (token) => {
      this.recaptchaToken = token
      console.log('reCAPTCHA验证成功,token:', token)
    }
  },
  methods: {
    submitForm() {
      if (!this.recaptchaToken) {
        alert('请先完成reCAPTCHA人机验证')
        return
      }
      // 执行前端提交逻辑
      console.log('准备提交,携带token:', this.recaptchaToken)
    }
  }
}
</script>

重要注意事项

Google reCAPTCHA 的官方设计要求后端验证 token 的有效性,仅前端验证只能阻挡基础的机器人请求,无法防止恶意用户伪造或篡改 token。如果你的场景对安全性要求较高,建议后续补充后端验证逻辑。

内容的提问来源于stack exchange,提问作者Ali Nawaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 05:25:23