【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;
  }
};

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当你在Vue3中全局封装axios时,你可以按照以下步骤进行操作: 1. 首先,安装axios依赖: ``` npm install axios ``` 2. 在你的项目中创建一个新的文件,例如`src/plugins/axios.js`,用于封装axios的配置和方法。 3. 在`axios.js`文件中,导入axios和Vue: ```javascript import axios from 'axios'; import { reactive } from 'vue'; ``` 4. 创建一个新的axios实例,并设置一些默认配置。在这里,你可以根据需要进行自定义配置。 ```javascript const http = axios.create({ baseURL: 'http://api.example.com', // 设置基本的请求URL timeout: 5000, // 设置请求超时时间 headers: { 'Content-Type': 'application/json', // 设置请求头 }, }); ``` 5. 创建一个全局Vue插件,将axios实例添加Vue的原型中,以便在整个应用程序中可以直接使用: ```javascript export default { install: (app) => { app.config.globalProperties.$http = http; }, }; ``` 6. 在你的Vue应用程序的入口文件(例如`src/main.js`)中使用该插件: ```javascript import { createApp } from 'vue'; import axiosPlugin from './plugins/axios'; const app = createApp(App); app.use(axiosPlugin); app.mount('#app'); ``` 7. 现在,你可以在任何组件中通过`this.$http`来直接使用axios实例发送请求了。例如: ```javascript export default { mounted() { this.$http.get('/api/data') .then(response => { console.log(response.data); }) .catch(error => { console.error(error); }); }, }; ``` 通过以上步骤,你就可以在Vue3中全局封装axios并使用了。这样,你在任何组件中都可以直接使用`this.$http`来发送请求,而不需要每次都导入axios库。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值