【问题标题】:Using the data retrieved from Axios call使用从 Axios 调用中检索到的数据
【发布时间】:2018-03-07 20:11:46
【问题描述】:

我正在尝试使用从 axios 调用中检索到的数据。我在响应中得到了正确的信息,但是当我尝试返回响应时,我在调用函数中未定义。有没有其他方法可以将 response.data 返回给调用函数?

  static getRequest(url) {
require('es6-promise').polyfill();
 axios({
  method: 'get',
  url: url,
  responseType:'json',
  withCredentials: true
})
  .then(response => {
   console.log(response.data);

    return response.data;
  })
  .catch(error => {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log('___________ERROR RESPONSE__________');
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log('_________ERROR REQUEST_______');
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an 
      Error
      console.log('Error', error.message);
    }
    console.log('_________ERROR CONFIG_________');
    console.log(error.config);
  });
}

【问题讨论】:

    标签: javascript axios


    【解决方案1】:

    您还需要从您的getRequest 函数返回您的axios 调用。

    在您上面的代码中,您只返回您的 axios 承诺。以下代码将在调用getRequest 时返回response 的值。

    static getRequest(url) {
    
        return axios({
          method: 'get',
          url: url,
          responseType:'json',
          withCredentials: true
        }).then(response => {
           return response.data
        })
    
        //rest of code here
    }
    

    【讨论】:

      猜你喜欢
      • 2020-05-10
      • 2019-01-24
      • 1970-01-01
      • 1970-01-01
      • 2019-04-22
      • 2020-06-18
      • 2012-01-04
      • 2022-11-24
      • 2018-04-01
      相关资源
      最近更新 更多