【问题标题】:Getting 400 error status code on client_credentials Spotify API request在 client_credentials Spotify API 请求上获取 400 错误状态代码
【发布时间】:2019-12-04 10:33:36
【问题描述】:

我正在处理 Spotify 的 API,但未能成功自动获取新的访问令牌。

function api() {
  $.ajax({
    type: 'POST',
    url: 'https://accounts.spotify.com/api/token?grant_type=client_credentials',
    headers: {
    'Authorization': 'Basic myClientIdEncodedToBase64Format:myClientSecretEncodedToBase64Format'
     },
    success: function(data) {
     console.log('Succes ->', data);
    },
    error: function(error) {
      console.log('Error -> ', error);
    }
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

我收到 400 错误。 If [i refer the doc][1], '400: Bad Request - 由于语法错误,服务器无法理解请求。邮件正文将包含更多信息。

我在这里做错了什么?

谢谢!

【问题讨论】:

  • 您的伪代码似乎暗示您正在分别对 clientId 和 clientSecret 进行 base64 编码,然后将它们连接起来。这是错误的。您需要首先将它们连接在一起,然后对整个字符串进行base64编码。
  • 查看此链接下表格的“标头参数”部分:developer.spotify.com/documentation/general/guides/…
  • 另外,根据那个链接grant_type应该在请求正文中发送,而不是在URL中
  • 谢谢@RoryMcCrossan ;)。所以我把 myClientId:myClientSecret 放在一个 base64 转换器中,然后在我的标题中粘贴下一个“基本”。对于 grant_type,我将其从 url 中删除(现在它看起来像 -> url: 'accounts.spotify.com/api/token')并在下面的一行中放置了 grant_type: 'client_credentials' 。又怎么了?
  • 请编辑问题以显示您的新代码。听起来您需要将grant_type 放在请求的data 属性中,而不是它自己的

标签: javascript jquery api spotify


【解决方案1】:

这是我的代码。我添加数据:

function api() {
          $.ajax({
            type: 'POST',
            url: 'https://accounts.spotify.com/api/token', 
            data: 'grant_type=client_credentials',
            headers: {
              'Authorization': 'Basic myClientIdAndMyClientSecretConvertedToBase64'
            },
            success: function(data) {
              console.log('Succes ->', data);
            },
            error: function(error) {
              console.log('Error -> ', error);
            }
          });
        }

【讨论】:

  • 哦,很好!有用 !数据参数“data: 'grant_type=client_credentials'”有效。但是在浏览器的网络窗口中,我预览了类似“invalid_client”的响应。当我转换我的 client_id 和我的 client_secret 时,只有一个空格无法与 API 匹配:)
猜你喜欢
  • 1970-01-01
  • 2017-08-10
  • 1970-01-01
  • 2020-04-25
  • 1970-01-01
  • 2017-09-06
  • 2017-10-19
  • 2018-06-07
  • 2020-10-21
相关资源
最近更新 更多