Created
July 13, 2017 07:50
-
-
Save lukasborawski/0ea98ce6973b8189dfa30544a2fc8f60 to your computer and use it in GitHub Desktop.
Nuxt.js Axios Plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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