【问题标题】:Spotify API Node.jsSpotify API Node.js
【发布时间】:2020-07-06 11:58:56
【问题描述】:

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

 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)

【问题讨论】:

  • 试试'Authorization': 'Bearer '+keys.spotifyClientId
  • 这似乎不起作用。我试过了
  • 错误变为401错误。不知道怎么解决这个问题
  • spotifyClientId 听起来不对,它应该是一个有效的访问令牌。请参阅文档:developer.spotify.com/documentation/general/guides/…
  • 访问令牌是否与clientID不同? ClientID 本质上就是我从开发者控制台制作的 API Key

标签: javascript node.js api spotify


【解决方案1】:

您得到的错误是 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 中的所有内容都将被调用。您可以打印错误或以任何其他方式处理它。

【讨论】:

  • @MangaldeepPannu 可以吗?
猜你喜欢
  • 2015-05-18
  • 2021-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-05
  • 2015-04-13
  • 2021-09-27
相关资源
最近更新 更多