javascript - 如何在 nuxt 中使用 Axios 模块和 vuejs 设置 header

标签 javascript vue.js axios nuxt.js

我试图在 vue.js 中为我的 SPA 定义一个“Accept-Language” header 。 (与 nuxt )。

这是我尝试过的方法,但它不起作用。我指定我使用 axios module for nuxt .

我创建了一个插件 explained in the documentation .我将该插件包含在 nuxt.config.js 中。

我尝试按照说明使用 setHeader here , 但它不起作用。

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;
        });
    }

关于javascript - 如何在 nuxt 中使用 Axios 模块和 vuejs 设置 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59747706/

相关文章:

javascript - 'inject' Angular 和 Jasmine 错误

javascript - 如何在使用window.open打开的弹出窗口中隐藏url

Vue.js 使用 @input 事件发送索引

vue.js - 为什么 Vue3 路由器不传递带有参数的 Prop ?

Firebase Cloud Functions 和 Busboy 不解析字段或文件

javascript - 在 promise 中执行 forEach 异步请求吗?

javascript - Puppeteer 无法可视化完整的 SVG 图表

typescript - Bootstrap Vue 阻止/取消事件

javascript - axios "url"参数必须是字符串类型。收到类型未定义错误

vue.js - 在 Vue.js 3 中通过 Axios 调用 API 登录时如何隐藏凭据?