View app.js
// before | |
db.all(`SELECT * FROM POSTS WHERE ID = ${req.params.id};`, function( | |
err, | |
row | |
) { | |
res.send(row); | |
}); | |
// after |
View app.js
created: function () { | |
axios.interceptors.response.use(undefined, function (err) { | |
return new Promise(function (resolve, reject) { | |
if (err.status === 401 && err.config && !err.config.__isRetryRequest) { | |
// if you ever get an unauthorized, logout the user | |
this.$store.dispatch(AUTH_LOGOUT) | |
// you can also redirect to /login if needed ! | |
} | |
throw err; | |
}); |
View main.js
const token = localStorage.getItem('user-token') | |
if (token) { | |
axios.defaults.headers.common['Authorization'] = token | |
} |
View router.js
import store from '../store' // your vuex store | |
const ifNotAuthenticated = (to, from, next) => { | |
if (!store.getters.isAuthenticated) { | |
next() | |
return | |
} | |
next('/') | |
} |
View auth.module.js
const actions = { | |
[AUTH_REQUEST]: ({commit, dispatch}, user) => { | |
return new Promise((resolve, reject) => { | |
commit(AUTH_REQUEST) | |
axios({url: 'auth', data: user, method: 'POST' }) | |
.then(resp => { | |
const token = resp.data.token | |
localStorage.setItem('user-token', token) | |
// Add the following line: | |
axios.defaults.headers.common['Authorization'] = token |
View logout.js
methods: { | |
logout: function () { | |
this.$store.dispatch(AUTH_LOGOUT) | |
.then(() => { | |
this.$router.push('/login') | |
}) | |
} | |
}, |
View logout.js
const actions = { | |
... | |
[AUTH_LOGOUT]: ({commit, dispatch}) => { | |
return new Promise((resolve, reject) => { | |
commit(AUTH_LOGOUT) | |
localStorage.removeItem('user-token') // clear your user's token from localstorage | |
resolve() | |
}) |
View auth.module.js
// basic mutations, showing loading, success, error to reflect the api call status and the token when loaded | |
const mutations = { | |
[AUTH_REQUEST]: (state) => { | |
state.status = 'loading' | |
}, | |
[AUTH_SUCCESS]: (state, token) => { | |
state.status = 'success' | |
state.token = token | |
}, |
View auth.module.js
const actions = { | |
[AUTH_REQUEST]: ({commit, dispatch}, user) => { | |
return new Promise((resolve, reject) => { // The Promise used for router redirect in login | |
commit(AUTH_REQUEST) | |
axios({url: 'auth', data: user, method: 'POST' }) | |
.then(resp => { | |
const token = resp.data.token | |
localStorage.setItem('user-token', token) // store the token in localstorage | |
commit(AUTH_SUCCESS, token) | |
// you have your token, now log in your user :) |
View auth.module.js
const getters = { | |
isAuthenticated: state => !!state.token, | |
authStatus: state => state.status, | |
} |
NewerOlder