使用从 Axios 调用中检索到的数据
Using the data retrieved from Axios call
我正在尝试使用从 axios 调用中检索到的数据。我在响应中得到了正确的信息,但是当我尝试 return 响应时,我在调用函数中得到了 undefined 。 return 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);
});
}
您还需要 return 从 getRequest
函数调用 axios
。
在您上面的代码中,您只是 returning 您的 axios 承诺。当调用 getRequest
时,以下代码将 return response
的值。
static getRequest(url) {
return axios({
method: 'get',
url: url,
responseType:'json',
withCredentials: true
}).then(response => {
return response.data
})
//rest of code here
}
我正在尝试使用从 axios 调用中检索到的数据。我在响应中得到了正确的信息,但是当我尝试 return 响应时,我在调用函数中得到了 undefined 。 return 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);
});
}
您还需要 return 从 getRequest
函数调用 axios
。
在您上面的代码中,您只是 returning 您的 axios 承诺。当调用 getRequest
时,以下代码将 return response
的值。
static getRequest(url) {
return axios({
method: 'get',
url: url,
responseType:'json',
withCredentials: true
}).then(response => {
return response.data
})
//rest of code here
}