Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

223
Vistas
How to access Vue component data and router from external javascript functions?

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)
        }
    }
about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda