繁体   English   中英

使用axios返回undefined的GET请求

[英]GET request with axios returning undefined

我正在尝试使用以下内容执行get请求:

router.get('/marketUpdates',((request, response) => {
  console.log("market updates");
  var data: Order[]
  axios.get('http://localhost:8082/marketUpdates')
  .then(function (response) {
    console.log("GET Response")
    console.log(response.data);
    data = response.data;
  })
  .catch(function (error) {
    console.log("Error in fetching market updates");
  });  

  console.log("Data before sending is ")
  console.log(data);
  response.send(data);
}))

但是,我在底部附近的console.log在.then中的console.log之前执行。

数据在发送时未定义。 有谁知道我怎么能避免这个?

  1. 代码是异步的,因此请求下面的所有代码都会在请求等待响应时执行。 你可以从axios.get的底部avoe移动日志
  2. 你内部的数据then是不一样的data ,你要发送...您正在使用function(response) ,而不是箭头FUNC。 (response) => {}所以你绑定另一个。

试试这种方式:

router.get('/marketUpdates',((request, response) => {
  console.log("market updates");
  let data: Order[]
  console.log("Data before sending is ")
  console.log(data);
  axios.get('http://localhost:8082/marketUpdates')
  .then((getResponse) => {
    console.log("GET Response")
    console.log(getResponse.data);
    data = getResponse.data;
    response.send(data);
  })
  .catch(function (error) {
    console.log("Error while fetching market updates");
  });  
}))

发送到服务器的请求始终是异步的。 这意味着,当服务器响应时,将执行函数.then()

让我重新格式化你的代码:

router.get('/marketUpdates',((request, response) => {
  console.log("market updates");

  var data: Order[];

  console.log("Data before sending is ")
  console.log(data);

  axios.get('http://localhost:8082/marketUpdates')
  .then((response) => {
    console.log("GET Response")
    console.log(response.data);
    data = response.data;

    response.send(data);
  })
  .catch(function (error) {
    console.log("Error in fetching market updates");
  });  
}))

使用axios.get('http://localhost:8082/marketUpdates')您将向服务器发出请求,服务器将响应,但这需要时间。 当程序等待服务器响应时,JavaScript不会阻止它执行该功能以保持用户界面运行。

因此.get返回一个Promise,它包含几个在不同场景中调用的函数。 只要服务器返回200和响应.then就会调用作为.then第一个参数给出的函数。

这意味着只要axios触发对服务器的调用,就会执行代码底部的日志。 此时没有数据,因为服务器尚未响应。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM