Home > Net >  How do I wait for an axios response and apply the response value to a redirect?
How do I wait for an axios response and apply the response value to a redirect?

Time:05-12

How do I make this method wait for the axios response and then apply the value for redirection?. The response for the http request is a JSON.

async process(p) {
    console.log('About to Call API');
    console.log('Calling HTTP Service');

    try {
        const t = await axios.get("http://sampleendpoint-inside-intranet.net/apiservice?param=" p)    
        
        //var redirectURL = t.redirectURL;
        //window.location.href = redirectURL;
        return '';

    }catch(error) {
        console.log(error);
        return 'error';
    }
    

CodePudding user response:

The response data is in t.data, you can try logging the response to see what it consists of, and then after that you can redirect using window.location.href = 'some_url'.

async process(p) {
    console.log('About to Call API');
    console.log('Calling HTTP Service');

    try {
        const t = await axios.get("http://sampleendpoint-inside-intranet.net/apiservice?param=" p)

        console.log(t.data); // You can log the data to check what data you get returned here
        window.location.href = t.data.redirectUrl;
    } catch(error) {
        console.log(error);
        return 'error';
    }
}

CodePudding user response:

You can use .then after you axios.get function. This will get executed as soon as you get the response.

const t = await axios.get("http://sampleendpoint-inside-intranet.net/apiservice?param=" p)
  .then((response) => {
     console.log(response.data);
   })
  .catch((error) => {
    console.log(error);
    return 'error';
  })

In the example above I logged the response.

You can also use the .catch so you don't need a try catch anymore

  • Related