[英]How to set an header with Axios module and vuejs in nuxt
I'm trying to define an "Accept-Language" header for my SPA in vue.js (with nuxt ).我正在尝试在vue.js (使用nuxt )中为我的 SPA 定义一个“Accept-Language”标头。
Here's what I tried but it doesn't work.这是我尝试过但不起作用的方法。 I specify that I use the axios module for nuxt .
我指定我对nuxt使用axios 模块。
I created a plugin as explained in the documentation .我按照文档中的说明创建了一个插件。 I included the plugin in nuxt.config.js.
我将插件包含在 nuxt.config.js 中。
I tried to use setHeader
as explained here , but it doesn't work.我尝试按照此处的说明使用
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)
}
});
}
But this code doesn't work.但是这段代码不起作用。 However, when I make
console.log
, I see them so it is taken into account.但是,当我制作
console.log
,我会看到它们,因此将其考虑在内。
Use $axios.interceptors instead of $axios.onRequest使用$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;
});
}
how are you making the request?你是如何提出请求的? If you want to use the helpers (setHeader, setToken, ...) provided by @nuxtjs/axios, you then must always use the request helpers provided by it, that are simply the lowercase http method names prefixed with a $
如果您想使用@nuxtjs/axios 提供的帮助程序(setHeader、setToken、...),那么您必须始终使用它提供的请求帮助程序,即以 $ 为前缀的小写 http 方法名称
Instead of $axios.get( ... )
use $axios.$get( ... )
and so on for put, post, delete...而不是
$axios.get( ... )
使用$axios.$get( ... )
等等来放置,发布,删除......
You can also try setting headers this way:您也可以尝试以这种方式设置标题:
$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.