使用从Axios调用中检索的数据

时间:2017-09-26 14:30:13

标签: javascript axios

我正在尝试使用从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);
  });
}

1 个答案:

答案 0 :(得分:3)

您还需要从axios功能返回getRequest来电。

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

static getRequest(url) {

    return axios({
      method: 'get',
      url: url,
      responseType:'json',
      withCredentials: true
    }).then(response => {
       return response.data
    })

    //rest of code here
}