I am new to Vue. I am trying to build a sort of middleware where I can check for all the status codes and handle it the wait I want.
I want to use this function everywhere I send a request to the backend. To prevent code duplication, im using a middleware function.
the function:
module.exports.serverErrorMiddleware = async (res)=>{
const status = res.status;
if(status == 500) return router.push('/error') //problem 1
if(status == 404) return router.push('/notfound')
if(status == 302) return router.push('/login')
if(status == 403 && !(res.error.isrefTokenError)) return router.push('/unauthorized')
if(status == 400) this.error = res.error.message // problem 2
if(status == 401){
if(!localStorage.getItem('refresh_token')) return router.push('/login')
try{
const response =
await axios({
method : 'get',
url : 'http://localhost:5000/api/auth/newtoken'
})
localStorage.setItem('access_token' , response.auth.accessToken);
}catch(err){
if(err.response.status == 403 && err.response.error.isrefTokenError) return router.push('/login');
router.push('/error')
}
}
}
problem 1 : I want to push a new route into the router for redirects but dont know how to access the router
problem 2 : I want to change the data in the Vue component from this function. I want to show the error to the user according to the error I receive from the server. So I want to access the error property in data of the component this function is called from.
I call this function in the catch of axios request
async submitForm(event){
event.preventDefault()
try{
const response = await axios({
method : 'post',
url : 'http://localhost:5000/api/auth/register',
data : {
username : this.formData.username,
password : this.formData.password
}
})
console.log(response)
}catch(err){
serverErrorMiddleware(err.response)
}
}