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

问题描述

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

解决方法

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...