Bootstrap

【vue3】全局封装Goole Recaptcha为接口添加自定义人机校验

本文主要是前端接入Goole Recaptcha实现人机校验,并封装成全局的配置方便特定接口使用,例如调用接口时只需要传递{verifyBehavior: true}参数即可开启接口人机校验,无需为每个接口单独封装,降低维护成本与心智负担


本意想的是直接在axios请求拦截器中调用executeRecaptcha直接把Token塞到请求头里,但是发现useReCaptcha环境不满足其依赖的上下文条件,又想着在main.ts中初始化然后导出给axios使用,但是发现还是不行,到此为止估计是useReCaptcha只能在组件环境中初始化了,所以塞到App.vue里初始化然后导出使用,分析结束,开始实行


基础的准备工作就不啰嗦了,自行百度即可,我们直接开始封装集成

//main.ts
import { createApp } from "vue";
import App from "./App.vue";
import {VueReCaptcha} from 'vue-recaptcha-v3'
const app = createApp(App);
app.use(VueReCaptcha, {
  siteKey: '替换成你的siteKey',
  loaderOptions: {
    useRecaptchaNet: true,
  }
});
app.mount("#app");
//App.vue
<script  lang="ts">
import { onMounted, ref } from 'vue';
import { useReCaptcha } from 'vue-recaptcha-v3';
let executeRecaptcha:any = null;
export default {
  name: 'App',
  setup() {
    onMounted(() => {
      // @ts-ignore
      const { executeRecaptcha: recaptcha } = useReCaptcha();
      if (recaptcha) {
        executeRecaptcha = recaptcha;
      } else {
        console.error("executeRecaptcha is undefined.");
      }
    });
  }
};

export async function getRecaptchaToken(action:any) {
  if (executeRecaptcha) {
    return await executeRecaptcha(action);
  }
  throw new Error("Recaptcha not initialized");
}
</script>


<template>
  <router-view v-slot="{ Component, route }" class="app">
    <component :is="Component" :key="route.fullPath" />
  </router-view>
</template>
//axios/index.ts
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import {getRecaptchaToken} from '@/App.vue'

// 创建 Axios 实例
const http = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  headers: {
    "Content-Type": "application/json",
  },
  timeout: 300000,
});

// 请求拦截器
 http.interceptors.request.use(
  async (config: any) => {
    const token = sessionStorage.getItem("token");

    if (config.verifyBehavior) {
      const googleResponseToken = await getRecaptchaToken('login'); // 获取 Google-Response token
      config.headers = {
        ...config.headers,
        "Google-Response": googleResponseToken,
      };
    }
    if (token) {
      config.headers.token = `${token}`;
    }
    return config;
  },
  (error) => {
    ElMessage.error("请求错误", error);
    return Promise.reject(`请求错误${error}`);
  }
);



export default http;

到此为止封装就结束了,下面示例如何为接口开启人机验证,添加{ verifyBehavior: true }即可,关闭验证传个false,默认关闭

import { AxiosRequestConfig } from "axios";
import http from "../index";

// 发送邮箱验证码

interface MyAxiosRequestConfig extends AxiosRequestConfig {
  verifyBehavior?: boolean;
}
export const emailver = async (data: any) => {
  try {
    const config: MyAxiosRequestConfig = { verifyBehavior: true };
    const response = await http.post(
      "发送邮箱验证码api接口",
      data,
      config
    );
    return response.data;
  } catch (error) {
    console.error("emailver error data:", error);
    throw error;
  }
};

// 注册账号
export const requestRegister = async (data: any) => {
  try {
    const config: MyAxiosRequestConfig = { verifyBehavior: true };
    const response = await http.post("注册api接口", data,config); //
    return response.data;
  } catch (error) {
    console.error("register error data:", error);
    throw error;
  }
};

;