首页 > 解决方案 > 尝试访问 Spotify API 时未定义 json

问题描述

我正在尝试使用 Spotify API 中的客户端凭据流获取访问令牌。我有以下代码

let oAuthOptions = {
  url: 'https://accounts.spotify.com/api/token',
  method: 'POST',
  headers: {
    'Authorization' : 'Basic ' + btoa(CLIENT_ID+':'+CLIENT_SECRET)
  },
  grant_type: 'client_credentials',
  redirect_uri: 'http://localhost:8888/callback ',
};

fetch(oAuthOptions)
  .then(response => response.json())
  .then(response => {
      console.log(response)  
});

我得到一个未定义的 json,但我不知道为什么,ID 和客户端密码都可以,因为我已经尝试使用编码基数的 curl 并且它可以工作。我试过使用 response.body.json(),但它报告错误response.body.json is not a function

标签: javascriptjsonreactjsauthenticationecmascript-6

解决方案


尝试在 Promise 中添加 acatch(error)以检查发生了什么:

fetch(url, oAuthOptions)
  .then(response => response.json())
  .then(response => {
      console.log(response)  
   })
  .catch(e => console.log("Error:", e));

如果错误是“SyntaxError: Unexpected token < in JSON at position 0”,则响应不是 JSON 有效数据。在这种情况下,请尝试返回response.text()以查看纯文本响应:

fetch(url, oAuthOptions)
  .then(response => response.text())
  .then(response => {
      console.log(response)
   })

在您的情况下,网址是https://accounts.spotify.com/api/token. 看起来响应没有 CORS 策略,因此如果您从网站中的未知主机调用它,它将被阻止。

https://jsfiddle.net/tjan64w8/


推荐阅读