PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 13, 2022

[FIXED] How to redirect to an error page depending on the response code

 October 13, 2022     axios, javascript, vue-router, vue.js     No comments   

Issue

I have an api that I use to check the weather, but it may return different codes depending on the situation. In my axios.get in the catch block I want to redirect the user to an error page depending on the code returned by the server. How can this be done? I tried code below but it works wrong. When an error occurs, first the 'cityDoesntExist' page appears and then almost immediately the 'serverDoesntWork' page

methods: {
    async getWeather() {
        const cityName = this.$route.params.cityName;
        await axios.get(`/api/weather`, {params: { cityName: cityName }})
            .then(response => response.data)
            .then(data => this.weather = data)
            .catch(function (error) {
                if(error.response.status === 404) {
                    router.push({name: 'cityDoesntExist'});
                }
                if(error.response.status === 500) {
                    router.push({name: 'serverDoesntWork'});
                }

            });
    },
},

Solution

Finally, after 4 hours i found solution and it was easier, than i thought. Thanks everybody who tried to help me! Here is my solution:

async getWeather() {
       const cityName = this.$route.params.cityName;
       await axios.get('/api/weather', {params: {cityName},})
           .then(response => response.data)
           .then(data => this.weather = data)
           .catch(function (err) {
               let errJSON = err.toJSON();
               console.log(errJSON);
               if (errJSON.status === 404) {
                   return router.push({name: 'cityDoesntExist'});
               } else if (errJSON.status === 500) {
                   return router.push({name: 'serverDoesntWork'});
               }
           });
   }


Answered By - Cygnus_bewickii
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing