【问题标题】:Axios interceptor not working when extending Nuxt Auth plugin扩展 Nuxt Auth 插件时 Axios 拦截器不起作用
【发布时间】:2021-01-22 23:54:38
【问题描述】:

我有一个像这样的 Axios 插件:

export default function ({ $axios, $auth }) {
  $axios.interceptors.request.use((req) => {
    req.data = {
      data: {
        // some data
      }
    }
    console.log('auth: ', $auth)

    return req
  })

  $axios.defaults.headers['Content-Type'] = 'application/vnd.api+json'
  $axios.defaults.headers.Accept = 'application/vnd.api+json'
}

在我的 nuxt.config 我有:

plugins: [
  { mode: 'client', src: '~/plugins/axios' }
],

当我运行我的请求时,我得到一个auth undefined。

所以我尝试扩展Nuxt Auth plugin:

auth.js:

export default function ({ $auth }) {
  if ($auth.loggedIn) {
    console.log('loggin in')
  } else {
    console.log('not loggin in')
  }
}

nuxt.config.js:

plugins: [
  // { mode: 'client', src: '~/plugins/axios' }
],

auth: {
  plugins: [{ src: '~/plugins/axios', ssr: true }, '~/plugins/auth.js'],
  // strategies etc..
}

所以我评论了 Axios 插件,并将它添加到了 auth 部分,如 Nuxt Auth 文档中所示。当我运行请求时,它不会记录 console.log('auth: ', $auth) 跳过整个 $axios.interceptors.request.use((req) => {

【问题讨论】:

    标签: axios nuxt.js nuxt-auth


    【解决方案1】:

    最后,我有机会帮助某人 XD #just-signed-up。 这是我用来从 axios 拦截器中访问身份验证的代码

    nuxt.config.js

    auth: {
      plugins: [{ src: '~/plugins/axios.js', ssr: true }, '~/plugins/auth.js']
    }
    

    auth.js

    export default function ({ $auth }) {
        if ($auth.loggedIn) {
            return true
        } else {
            return false
        }
    }
    

    axios.js

    export default function ({ $axios, redirect, $auth }) {
      $axios.onRequest(config => {
        console.log('Making request to ' + config.url)
      })
    
      $axios.onError(error => {
        const code = parseInt(error.response && error.response.status)
        if (code === 401) {
          if ($auth.loggedIn) {
            $auth.logout()
          }
          redirect('/login');
        }
        if (code === 404) {
          redirect('/404')
        }
      })
    }
    

    【讨论】:

      猜你喜欢
      • 2023-02-08
      • 2020-06-04
      • 2020-07-26
      • 2020-02-28
      • 2020-06-23
      • 2018-11-06
      • 1970-01-01
      • 1970-01-01
      • 2019-09-19
      相关资源
      最近更新 更多