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

Vue3 Laravel11项目中vform无法发送Bearer Token问题

解决vform无法携带自定义axios实例Bearer Token的问题

核心原因

vform会在实例初始化阶段基于axios实例构建请求逻辑,若在表单创建后再赋值axios属性,无法触发内部配置更新,导致自定义axios的拦截器未被正确应用。

解决方案

1. 初始化vform时直接传入自定义axios实例

创建表单实例时,通过第二个参数传入axios配置,确保vform从一开始就使用你的自定义实例:

import axiosInstance from '@/plugins/axios'
import Form from 'vform'

// 初始化表单时绑定axios实例
this.assignmentForm = new Form(
  {
    // 表单字段
    title: '',
    description: ''
  },
  { axios: axiosInstance } // 关键:这里传入自定义axios
)

2. 全局配置vform使用自定义axios

在项目入口文件(如main.js)中全局设置vform的axios实例,避免每个表单都单独配置:

import { createApp } from 'vue'
import App from './App.vue'
import axiosInstance from '@/plugins/axios'
import Form from 'vform'

// 全局绑定自定义axios到vform
Form.axios = axiosInstance

const app = createApp(App)
app.use(Form)
app.mount('#app')

3. 检查自定义axios插件的拦截器配置

确保拦截器是绑定到你创建的axios实例上,而非全局axios:

// @/plugins/axios.js
import axios from 'axios'

const axiosInstance = axios.create({
  baseURL: import.meta.env.VITE_APP_API_URL
})

// 给实例添加请求拦截器
axiosInstance.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => Promise.reject(error)
)

export default axiosInstance

4. 临时方案:手动给vform的axios实例添加拦截器

若上述方法无效,可在表单初始化后手动添加拦截器(不推荐长期使用,优先用前两种方法):

this.assignmentForm = new Form({
  // 表单字段
})

// 手动添加拦截器到vform的axios实例
this.assignmentForm.axios.interceptors.request.use(config => {
  const token = localStorage.getItem('token')
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 02:05:02