[英]json undefined when trying to acces to Spotify API
我正在尝试使用 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
尝试在承诺中添加一个catch(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)
})
在您的情况下,URL 是https://accounts.spotify.com/api/token
。 响应似乎没有 CORS 策略,因此如果您从网站中的未知主机调用它,它将被阻止。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.