扩展 Nuxt Auth 插件时 Axios 拦截器不起作用

时间:2021-01-22 23:54:38

标签: axios nuxt.js nuxt-auth

我有一个像这样的 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) => {

1 个答案:

答案 0 :(得分:0)

最后,我有机会帮助某人 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')
    }
  })
}