Skip to content

Instantly share code, notes, and snippets.

@lukasborawski
Created July 13, 2017 07:50
Show Gist options
  • Save lukasborawski/0ea98ce6973b8189dfa30544a2fc8f60 to your computer and use it in GitHub Desktop.
Save lukasborawski/0ea98ce6973b8189dfa30544a2fc8f60 to your computer and use it in GitHub Desktop.
Nuxt.js Axios Plugin
import * as axios from 'axios'
import { getCookieInClient } from '../util/assist'
export default ({ app, store, redirect }) => {
// The server-side needs a full url to works
if (process.SERVER_BUILD) {
axios.defaults.baseURL = `http://${process.env.HOST || 'localhost'}:${process.env.PORT || 3000}`
}
// interceptors request
axios.interceptors.request.use(config => {
if (typeof document === 'object') {
let token = getCookieInClient('token')
if (token) {
config.headers.Authorization = token;
}
}
return config;
}, err => {
return Promise.reject(err);
});
axios.interceptors.response.use(response => {
if (response.data.code === 401) {
redirect('/login')
}
return response;
}, function (error) {
return Promise.reject(error);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment