axios get 请求挂起,没有错误,catch 未触发

god*_*har 6 spotify node.js express axios

当我在节点上使用 axios 发出 GET 请求时,它只是挂起,不会抛出 catch 并捕获错误。

我不知道如何调试这个,没有抛出错误。我正在启动 Spotify API,但如果那边出现问题,我肯定会得到一些响应吗?

有一段时间我收到了 ECONNRESET 错误,我的互联网不太稳定。但这个错误不再被抛出。

我尝试过使用 fetch,同样的问题。我又回到了经典的 Promise 语法。从现在起它一直运行良好。

该方法被调用并记录。

"node": "10.0.0",
"axios": "^0.19.0",
Run Code Online (Sandbox Code Playgroud)

    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;
            }
        });
    }

Run Code Online (Sandbox Code Playgroud)

'req 方法调用 ' 被记录并且信用在那里,没有别的,只是挂起。

cad*_*311 4

无需将调用存储在函数内。只需将通话视为承诺即可。

 function tryFetchForPlaylists(usersCred) {
        console.log('req method called ', usersCred)
        let playlistData;

        return axios.get('https://api.spotify.com/v1/users/' + usersCred.userId + '/playlists',
            {
                headers: {
                    'Authorization': 'Bearer ' + usersCred.accessToken,
                    'Content-Type': 'application/json'
                }
            })
            .then((data) => {
             // return your data here...
            })
            .catch((err) => {})


    }
Run Code Online (Sandbox Code Playgroud)

  • 我忘了‘返回’ axios 函数 - 该死!我会投票给你@caden311 (3认同)