如何在nuxt中使用Axios模块和Vue.js设置头部(header)

3
我正在尝试为我的vue.js单页应用程序(使用nuxt)定义一个“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时,我看到了它们,所以它被考虑在内。
2个回答

3

使用$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;
        });
    }

1
你是如何发起请求的?如果想要使用@nuxtjs/axios提供的帮助函数(setHeader、setToken等),那么你必须始终使用它提供的请求函数,即以小写http方法名称为前缀加上$符号的函数。
不要使用$axios.get(…),而是使用$axios.$get(…)等等put、post、delete等方法。
你也可以尝试通过以下方式设置标头:
$axios.onRequest(config => {
    const baseUrl = $axios.defaults.baseURL;

    const locale = store.getters['lang/locale'];

    if (locale) {
        config.headers.common['Accept-Language'] = locale;
    }
});


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接