How can I make a series of post requests for the consumption of an API? In between each request, the responses must be processed to return only what is of significance for the next step.
Example:
const obtenerTicket = async () => {
const respuesta = await axios.post('url', 'username=user&password=pass', {
headers:headers
}).then( (res) => {
const {headers, ...data} = res;
const arrayUrl = headers.location.split('/');
const secPath = arrayUrl[arrayUrl.length-1];
return secPath;
//En este momento quiero retornar esa variable para usarla en la URL de la proxima peticion
}).catch( (err) => {
console.log(err);
})
}
This response is a necessary part for the next post request:
const accesoServicio = async () => {
const path = await obtenerTicket();
path.then( (url) => {
axios.post(`url/${url}`, 'body', {
headers:headers
}).then( (res) => {
console.log(res)
}).catch ( (err) => {
console.log(err)
} )
} ).catch( (err) => {
console.log(err);
} )
}
});
And so on. The problem I am having is that when returning the values, the variables that I define in the body of the next functions are left as undefined.
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'then' of undefined
Thank you very much and I hope the question is understood.
What you should do is return the call to axios (which is a promise), like this:
And in this function you can remove the then, like so