nuxt-community / axios-module

Secure and easy axios integration for Nuxt 2
https://axios.nuxtjs.org
MIT License
1.2k stars 245 forks source link

Access new or existing axios instance in custom module #571

Open robertkabat opened 2 years ago

robertkabat commented 2 years ago

Hello,

I am trying to write my own custom NuxtJS module for pixie auth which uses Axios. The problem I have is that my custom module and plugin that lives inside of my module do not have access to Axios at all.

So the flow is this:

My custom module => registers my own plugin => in the plugin I would like to add an access token to each request and few more things...

This is my module

import path from 'path'

export default function (moduleOptions) {
  const { nuxt } = this

  this.addPlugin({
    src: path.resolve(__dirname, 'src/plugins/auth.js'),
    options: Object.assign({}, nuxt.options.pauth, moduleOptions)
  })
}

This is my plugin

import authModule from '~/modules/pauth/src/store/modules/auth/auth.js'
import { AuthService } from "~/modules/pauth/src/services/AuthService";
import axios from '@nuxtjs/axios';

export default({ app, store, $axios}, inject) => {
  store.registerModule('auth', authModule, { preserveState: !!store.hasModule('auth') })
  inject('auth', new AuthService(store, '<%= JSON.stringify(options) %>'))

  app.router.beforeEach((to, from, next) => {
    // const waitForStorageToBeReady = async (to, from, next) => {
    //   await store.restored
    // }

    let test = axios;
    console.log(test)
    // if user is logged in on the frontend check if the backend is ok
    // axios.post('is-logged').then(response => {
    //   console.log(response)
    // })

    next()
  })
}

Even when I use hooks and wait for all modules to load I can't seem to get that to work. I tried looking up how nuxt/auth does that but no luck.

Could someone advise me what to do?

donghoon-song commented 1 year ago

@robertkabat Why dont you use middleware?