[英]How to set an header with Axios module and vuejs in nuxt
我正在嘗試在vue.js (使用nuxt )中為我的 SPA 定義一個“Accept-Language”標頭。
這是我嘗試過但不起作用的方法。 我指定我對nuxt使用axios 模塊。
我按照文檔中的說明創建了一個插件。 我將插件包含在 nuxt.config.js 中。
我嘗試按照此處的說明使用setHeader
,但它不起作用。
export default function ({ store, $axios, redirect }) {
$axios.setBaseURL(process.env.BASE_URL);
if (process.server) {
return
}
$axios.onRequest(config => {
const baseUrl = $axios.defaults.baseURL;
const locale = store.getters['lang/locale'];
if (locale) {
$axios.setHeader('Accept-Language', locale)
}
});
}
但是這段代碼不起作用。 但是,當我制作console.log
,我會看到它們,因此將其考慮在內。
使用$axios.interceptors而不是 $axios.onRequest
export default function({store, $axios, redirect}) {
$axios.setBaseURL(process.env.BASE_URL);
if (process.server) {
return
}
$axios.interceptors.request.use((config) => {
const baseUrl = $axios.defaults.baseURL;
const locale = store.getters['lang/locale'];
if (locale) {
$axios.setHeader('Accept-Language', locale)
}
return config;
});
}
你是如何提出請求的? 如果您想使用@nuxtjs/axios 提供的幫助程序(setHeader、setToken、...),那么您必須始終使用它提供的請求幫助程序,即以 $ 為前綴的小寫 http 方法名稱
而不是$axios.get( ... )
使用$axios.$get( ... )
等等來放置,發布,刪除......
您也可以嘗試以這種方式設置標題:
$axios.onRequest(config => {
const baseUrl = $axios.defaults.baseURL;
const locale = store.getters['lang/locale'];
if (locale) {
config.headers.common['Accept-Language'] = locale;
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.