繁体   English   中英

Spotify API Node.js

[英]Spotify API Node.js

我试图在 node.js 中使用 axios 向 spotify API 发出获取请求。 但是,我总是收到一个 400 错误的请求。 有人可以帮我吗? 代码片段和错误粘贴在下面。

 app.get('/api/search', async (req, res) => {
        const spotify_search_one = await axios.get('https://api.spotify.com/v1/search', {
            headers: { 
                'Authorization': keys.spotifyClientId 
            }, 
            params: {
                q: "face",
                type: "track"
            } 
        });
        console.log(spotify_search_one);
    })

错误如下

 UnhandledPromiseRejectionWarning: Error: Request failed with status code 400
[0]     at createError (/Users/uddhavbhagat/Desktop/Projects/TuneIn/node_modules/axios/lib/core/createError.js:16:15)
[0]     at settle (/Users/uddhavbhagat/Desktop/Projects/TuneIn/node_modules/axios/lib/core/settle.js:17:12)
[0]     at IncomingMessage.handleStreamEnd (/Users/uddhavbhagat/Desktop/Projects/TuneIn/node_modules/axios/lib/adapters/http.js:236:11)
[0]     at IncomingMessage.emit (events.js:322:22)
[0]     at endReadableNT (_stream_readable.js:1187:12)
[0]     at processTicksAndRejections (internal/process/task_queues.js:84:21)
[0] (node:12697) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 4)

您遇到的错误是 Promise (axios.get) 没有问题。
因此,当 api 调用导致错误时,您不会以任何方式处理它。 以异步方式尝试它怎么样? 我会发送 api 调用axios.get('URL', ...)然后使用.then.catch.

我建议如下:

axios.get('https://api.spotify.com/v1/search', { headers: { 'Authorization': keys.spotifyClientId } })
     .then(response => {
           const spotify_search_one = response.data;
     }).catch(err => {
           console.error(err);
     })

这将向 Spotify-API 询问所需的数据,然后在 API 调用成功时执行您在.then中编写的任何内容。 变量response包含您可以使用response.data获得的数据(在本例中为搜索结果)。 如果 API 调用失败,将调用.catch中的所有内容。 您可以打印错误或以任何其他方式处理它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM