Express 为什么axios会在成功的Spotify API调用中捕获错误?
我在试图通过API向spotify添加歌曲时遇到了一个奇怪且令人沮丧的错误 API调用成功,歌曲添加正确,但返回“TypeError:无法读取未定义的属性“data” 这是我认为应该是正确的代码Express 为什么axios会在成功的Spotify API调用中捕获错误?,express,axios,spotify,netlify,Express,Axios,Spotify,Netlify,我在试图通过API向spotify添加歌曲时遇到了一个奇怪且令人沮丧的错误 API调用成功,歌曲添加正确,但返回“TypeError:无法读取未定义的属性“data” 这是我认为应该是正确的代码 router.post('/addSongs', async (req, res) => { var access_token = req.query.access_token; var playlist_id = req.query.playlist_id; var so
router.post('/addSongs', async (req, res) => {
var access_token = req.query.access_token;
var playlist_id = req.query.playlist_id;
var songs = req.body.songs;
try {
var retVal = await axios({
method: 'post',
url: `https://api.spotify.com/v1/playlists/${playlist_id}/tracks`,
headers: {
'Authorization': 'Bearer ' + access_token,
'Content-type': 'application/json'
},
data: {
uris: songs
}
});
res.send(retVal);
} catch (error) {
console.log(error.response.data);
res.status(error.response.status).send(error);
}
});
我发现的一个更令人沮丧的解决方案是,以下更改使其工作完美,尽管这让我感觉很糟糕:
...
} catch (error) {
res.status(200).send("whatever");
}
...
我使用的是Express和Netlify lambda,我对这一切都很陌生
请注意,它也可以正常工作,并在实际发生错误时打印错误状态和消息。如果我只打印错误,则会出现“将循环结构转换为JSON”错误。因此,如果有人发现此错误,我会解决它。问题是当我试图返回
retVal
变量时,axois抛出了一个错误。我认为这是一个空字符串
解决方案:
res.send(retVal)
change to:
res.status(201).send()
我猜响应没有主体,因此数据未定义,它只有一个响应代码,我假设在catch块中打印出您的
错误。