Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

nuxt.js - Axios interceptor not working when extending Nuxt Auth plugin

I have a Axios plugin like so:

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'
}

In my nuxt.config I have:

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

When I run my request I get a auth undefined.

So I try to extend the 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..
}

So I comment the Axios plugin, and I add it to the auth section as shown on the Nuxt Auth docs. When I run the request it doesn't log the console.log('auth: ', $auth) skipping the whole $axios.interceptors.request.use((req) => {

question from:https://stackoverflow.com/questions/65854306/axios-interceptor-not-working-when-extending-nuxt-auth-plugin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

finally, the chance for me to help someone out XD #just-signed-up. heres the code i use to access auth from within the axios interceptor

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...