i am using middleware to validate token to the server for every user moving page to page but it seems my ajax service can't get token from middleware because the ajax request in my middleware is too late to get token (race condition with my ajax service). this is my checkAuth Middleware
import { getUserFromCookie, getUserFromLocalStorage } from '~/utils/Auth'
const lodash = require('lodash')
const axios = require('axios')
// noinspection JSUnusedGlobalSymbols
export default function({ store, redirect, isServer, req, app }) {
if (isServer && !req) {
return
}
if (req && req.url === '/') {
return
}
if (lodash.isEmpty(store.state.auth.user)) {
let user
user = isServer ? getUserFromCookie(req) : getUserFromLocalStorage()
console.log(user)
try {
user = JSON.parse(user)
const options = {
method: 'POST',
url: `${process.env.USER_API}/validate-token`,
headers: {
'Content-Type': 'application/json',
'token': user.token
},
timeout: 2000,
data: null
}
// race condition in this ajax request
axios(options).then(function(response) {
if (response.data) {
store.commit('auth/SET_IS_LOGGED_IN', true)
store.commit('auth/setUser', user)
} else {
redirect('/')
}
}).catch(function(err) {
redirect('/')
})
} catch (err) {
redirect('/')
}
}
let locale = store.state.auth.user.appLanguage
if (!locale) locale = process.env.DEFAULT_LANGUAGE
store.commit('auth/SET_LANG', locale)
app.i18n.locale = locale
}
can anyone solve this... sorry for bad english
<!--cmty--><!--cmty_prevent_hook--><div align="right"><sub><em>This question is available on <a href="https://nuxtjs.cmty.io">Nuxt.js</a> community (<a href="https://nuxtjs.cmty.io/nuxt/nuxt.js/issues/c1916">#c1916</a>)</em></sub></div>