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

如何在Quasar的Axios启动文件中注入Bearer Token

在Quasar框架中为Axios自动注入Bearer Token并适配execute方法

问题背景

当前使用Quasar框架,已有默认的Axios启动文件axios.ts,希望实现类似目标代码中的execute方法——自动为每个请求注入Bearer Token,同时保留Quasar的启动文件结构规范,不清楚如何进行适配。

适配后的完整代码

以下是修改后的axios.ts文件,完美整合Quasar的boot机制和自动注入Token的execute方法:

import { boot } from 'quasar/wrappers';
import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $axios: AxiosInstance;
    $api: typeof api; // 定义$api的类型
  }
}

// 创建Axios实例
const client = axios.create({
  baseURL: 'https://localhost:44362/',
  headers: { 'Content-type': 'application/json' },
});

// 封装API请求方法
const api = {
  // 核心execute方法,自动注入Token
  async execute<T = any>(method: string, resource: string, data?: any): Promise<T> {
    // 从Quasar的auth插件获取Token(根据你的实际Auth方案调整)
    const accessToken = await window.$q?.auth?.getAccessToken();
    // 若使用Pinia/Vuex存储Token,替换为对应获取方式:
    // const accessToken = useAuthStore().accessToken;

    const config: AxiosRequestConfig = {
      method,
      url: resource,
      data,
      headers: {
        ...(accessToken && { Authorization: `Bearer ${accessToken}` }),
      },
    };

    return client(config).then((res) => res.data);
  },

  // 业务请求方法
  getAll<T = any>() {
    return this.execute<T>('get', '/');
  },
  getById<T = any>(id: string | number) {
    return this.execute<T>('get', `/${id}`);
  },
  create<T = any>(data: any) {
    return this.execute<T>('post', '/', data);
  },
  update<T = any>(id: string | number, data: any) {
    return this.execute<T>('put', `/${id}`, data);
  },
};

export default boot(({ app }) => {
  // 挂载全局属性
  app.config.globalProperties.$axios = axios;
  app.config.globalProperties.$api = api;
});

export { api };

关键说明

  1. 保留Quasar Boot结构:继续使用Quasar提供的boot函数,遵循框架全局插件初始化规范,避免SSR环境下的状态污染问题。
  2. TypeScript类型适配:扩展ComponentCustomProperties接口,为$api添加类型定义,保证Vue组件中使用时的类型提示与校验。
  3. Token获取灵活适配:根据你的实际鉴权方案调整Token获取逻辑,兼容Quasar官方Auth插件、Pinia/Vuex存储等多种场景。
  4. 健壮的请求封装:execute方法支持泛型,方便指定返回数据类型;同时处理Token不存在的情况,避免添加无效的Authorization请求头。
  5. 多场景使用支持:既将api挂载到Vue全局属性供Options API使用(this.$api),也导出api变量,方便在Composition API或非Vue文件中直接导入调用。

使用示例

  • 在Options API组件中:
<script>
export default {
  async mounted() {
    const data = await this.$api.getAll();
    console.log(data);
  },
};
</script>
  • 在Composition API组件中:
<script setup>
import { api } from 'src/boot/axios';

async function fetchData() {
  const data = await api.getAll();
  console.log(data);
}
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 13:32:53