如何让Inertia所有手动请求自动携带已配置的axios全局自定义请求头?
问题:Inertia手动请求无法自动携带自定义Axios请求头
我尝试让所有请求都携带自定义请求头Accept-Content-Language,该配置在常规axios请求中生效,但Inertia手动发起的请求不会携带此请求头。
设置请求头的代码:
import axios from 'axios'; const lang = localStorage.getItem('vue_i18n_locale'); if (lang) { axios.defaults.headers.common['Accept-Content-Language'] = lang; axios.defaults.headers.common['Accept-Language'] = lang; } window.axios = axios;
执行Inertia手动请求时:
$inertia.post('some-route', { some: data })
请求不会携带上述自定义头。我知道可以给每个手动请求传入header属性,但希望整个应用的所有Inertia请求自动携带该头,无需每次手动添加,请问有实现方法?
解决方案
方法1:让Inertia复用你配置好的Axios实例
Inertia默认会创建独立的Axios实例,因此你需要在初始化Inertia时指定使用你配置过的实例。以Vue3项目为例,在初始化文件(如app.js)中修改:
import { createApp, h } from 'vue' import { createInertiaApp } from '@inertiajs/vue3' import axios from 'axios'; // 先配置自定义请求头 const lang = localStorage.getItem('vue_i18n_locale'); if (lang) { axios.defaults.headers.common['Accept-Content-Language'] = lang; axios.defaults.headers.common['Accept-Language'] = lang; } createInertiaApp({ resolve: name => import(`./Pages/${name}.vue`), setup({ el, App, props, plugin }) { return createApp({ render: () => h(App, props) }) .use(plugin) .mount(el) }, // 关键:指定Inertia使用的Axios实例 axios: axios, })
这样所有Inertia请求都会自动继承你配置的全局请求头。
方法2:添加Inertia请求拦截器
如果不想替换整个Axios实例,可以通过Inertia的请求拦截器,在每个请求发送前注入自定义头:
import { Inertia } from '@inertiajs/vue3' const lang = localStorage.getItem('vue_i18n_locale'); // 拦截所有Inertia请求,注入语言头 Inertia.intercept('request', (config) => { if (lang) { config.headers['Accept-Content-Language'] = lang; config.headers['Accept-Language'] = lang; } return config; });
如果用户会动态切换语言,记得在语言切换时更新lang变量的值,或者重新设置拦截器里的请求头内容。
内容的提问来源于stack exchange,提问作者dannypas00
相关产品推荐
相关产品推荐

