【发布时间】:2019-07-19 15:04:26
【问题描述】:
当我在节点上使用 axios 发出 GET 请求时,它只是挂起,不会抛出 catch 并捕获错误。
我不确定如何调试它,没有抛出错误。我正在触发 spotify API,但如果那里有问题,我肯定会得到一些回应吗?
有一段时间我收到 ECONNRESET 错误,我的互联网不太稳定。但是这个错误不再被抛出。
我尝试过使用 fetch,同样的问题。我又回到了经典的 Promise 语法。从现在开始,它一直运行良好。
此方法被调用并记录。
"node": "10.0.0",
"axios": "^0.19.0",
function tryFetchForPlaylists(usersCred) {
console.log('req method called ', usersCred)
let playlistData;
try {
playlistData = axios.get('https://api.spotify.com/v1/users/' + usersCred.userId + '/playlists',
{
headers: {
'Authorization': 'Bearer ' + usersCred.accessToken,
'Content-Type': 'application/json'
}
});
} catch (err) {
console.log(err)
if (err.response.status === 401) {
console.error(err);
return {statusCode: 401};
}
}
playlistData.then((res) => {
console.info('response status',res.status)
if(res.status === 200) {
return res;
}
});
}
'req 方法称为 ' 被记录并且凭据在那里,没有别的,只是挂起。
【问题讨论】:
-
axios.get()返回一个承诺,而不是一个完成的值。您需要在该承诺上使用await或.then()以获得价值。而且,try/catch只会在您使用await时出现错误。否则,您应该使用.catch()来查看错误。 -
@jfriend00 如果我使用
.then()和.catch()似乎可以工作 - 我得到了 200 的 JSON,这一切都很好。但是将其返回到使用await的函数不起作用。 ` 让状态 = 等待 tryFetchForPlaylists(userCreds); console.log('等待状态', status)`的状态是undefined -
好吧
tryFetchForPlaylists()只是实现错误,所以你不能await它。你必须修复它的实现。似乎您需要阅读有关如何从 Promise 中获取错误的信息。try/catch仅适用于异步函数内的情况,并且承诺您正在使用await。如果您不使用await fetch(),则必须使用fetch().then().catch()来捕获错误。
标签: node.js express axios spotify