Home > Enterprise >  Wait for response in a request in axios
Wait for response in a request in axios

Time:12-22

I'm trying, in my Vue application with axios to run two requests, the second needs the information obtained in the first one, specifically the access_token.

I've tried something like

let access_token = '';
var config = {
    method: 'post',
    url: <url1>,
    data: <data>
    headers: {
      header1: <header>
      }
}

axios(config)
.then((response: any) => {
    access_token = response.access_token;
}

config = {
    method: 'post',
    url: <url2>,
    headers: {
      Authorization: `Bearer ${access_token}`
      }
}
axios(config);

The first request, as I see on the Network tab on the developer tools, is returning an access_token. However, when the second request is run, that access_token is empty and therefore the second one fails.

Any idea what I am missing here?

CodePudding user response:

you need to call the second request inside of .then() of the first request, which basically means to wait for the first request to finish before starting the second one:

const config = {
    method: 'post',
    url: <url1>,
    data: <data>
    headers: {
        header1: <header>
    }
}

axios(config).then((response: any) => {
    const access_token = response.data.access_token;

    const config = {
        method: 'post',
        url: <url2>,
        headers: {
            Authorization: `Bearer ${access_token}`
        }
    }
    axios(config).then(...);
}

CodePudding user response:

You need to wait for the first request to resolve Aka finished and then you can make the second request using async/await logic.

Here's the code-

async function req(){
let access_token = '';
var config = {
    method: 'post',
    url: <url1>,
    data: <data>
    headers: {
      header1: <header>
      }
}

const {data} = await axios(config);

access_token = data.access_token

config = {
    method: 'post',
    url: <url2>,
    headers: {
      Authorization: `Bearer ${access_token}`
      }
}

axios(config);

}
  • Related