E
E
Eugene2020-05-18 14:05:49
Vue.js
Eugene, 2020-05-18 14:05:49

How to add a plugin in vuejs similar to nuxt?

Found an example plugin for nuxt.js

export default function ({ $axios, redirect, store }) {
    $axios.interceptors.request.use(request => {
        if (store.getters['auth/isAuthenticated'] &&
            !request.headers.common.Authorization
        ) {
            const token = store.getters['auth/getToken']
            request.headers.common.Authorization = `Bearer ${token}`
        }
        
        return request
    })

    $axios.onError(error => {
        if (error.response) {
            if (error.response.status === 401) {
                redirect('/admin/login?message=session')
                store.dispatch('auth/logout')
            }

            if (error.response.status === 500) {
                console.error('server internal error')
            }
        }
    })
}


How to connect axios in vuejs to also implement the plugin? I tried to do it like this, but the linter complains about cyclic dependencies.
import axios from 'axios';
import store from '@/store';

const client = axios.create({
    baseURL: 'http://localhost:3000',
    timeout: 5000,
});

client.interceptors.request.use(request => {
    if (store.getters['auth/isAuth'] && !request.headers.common.Authorization) {
        const token = store.getters['auth/getToken'];
        request.headers.common.Authorization = `Bearer ${token}`;
    }

    return request;
});

export default client;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor, 2020-05-18
@loonny

On the documentation page VueJS - Plugins , it is written in detail

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question