Odasaku
Odasaku

Reputation: 367

NodeJs, Axios: Value of variable not updating with response from xhr request

I am making an xhr request in nodejs using Axios. And I am trying to save a value from this response to a variable, but it isn't working and I am not sure why.

Code:

let redirectUrl = 'placeholder'
axios.get(url)
      .then(res => {
        redirectURL = res.url
        console.log(res.url, "HERE")
      })
      .catch(err => console.log(err))
      return res.render('index',{url: redirectURL})

I have tried declaring redirectUrl in both global as var and local scope, but the value isn't changing, on index when I console log this value, it logs placeholder. index is index.jsx as I am using jsx as the template engine. Please let me know if I should provide any more information. Thank You in advance.

Upvotes: 0

Views: 792

Answers (2)

Supankar Banik
Supankar Banik

Reputation: 1

Axios is a promise-based HTTP client, So when javascript engine executes your code, it moves axios call to web API from callstack (line# 2) and then it starts to execute the last line return res.render('index',{url: redirectURL}) where redirectURL value is placeholder. You have to write all the logic in promise then method, like

axios
  .get(url)
  .then((data) => res.render("index", { url: data.url }))
  .catch((err) => {
    // error response
    console.log(err);
  });
  

Upvotes: 0

tam.teixeira
tam.teixeira

Reputation: 863

axios.get is an async call, so your return will use the original (placeholder) value instead of the new one. Normally to solve this kind of asynchronicities i use async/await

async function getRedirectURL(url) {
  try {
    const res = await axios.get(url);
    // Note that if you want some return value from axios call you access it by res.data
    console.log('res.url :', res.url, ". res.data:", res.data);
    return res.render('index',{url: res.data.url});
  } catch (err) {
    console.log(err);
    throw err;
  }
}
      

Upvotes: 1

Related Questions