javascript - 尝试访问 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
解决方案
尝试在 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 策略,因此如果您从网站中的未知主机调用它,它将被阻止。
推荐阅读
- python - 将带有整数的文件迭代到变量中(未知文件大小)
- python - 如何找到名称*部分
- javascript - 如何使用 Bootstrap 获取滑块中活动图像的 ID
- php - 使用 PHP 和 Postgresql 插入数据库
- c# - 创建匿名类型时如何使用临时本地数据?
- git - Git Merge:错误:无法取消旧链接
: 没有相应的文件和目录 - google-api - G-Suite API 为经销商购买许可证
- java - Selenium:将 WebElements 添加到列表中,然后检查所有这些元素的可见性
- python - 正则表达式 re.findall() 搜索以提取以 # 和邮政编码开头的单元
- servicestack - 如何在 Authenticate 消息中放置 Api 密钥?