Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

221
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!