javascript - 如何获得访问 token Spotify API?

标签 javascript html ajax xmlhttprequest spotify

几天来我一直在查看 Spotify api 和示例源代码,但我仍然无法弄清楚如何获取访问 token 来访问用户的播放列表数据。我已经到了拉起登录窗口,用户登录,然后我收到授权码的地步。在这一点上,我尝试做这样的事情:

window.open("https://accounts.spotify.com/api/token?
grant_type=authorization_code&code="+code+"&redirect_uri=myurl&client_id=3137b15
2f1424defa2c6020ae5c6d444&client_secret=mysecret");

$.ajax(
    {
      url: "https://accounts.spotify.com/api/token?grant_type=authorization_code&code="+code+"&redirect_uri=myurl&client_secret=mysecret&client_id=myid", 
      success: function(result){
        alert("foo");
      }
    }
);

但无论哪种方式,我都会得到这样的结果:

{"error":"server_error","error_description":"Unexpected status: 405"}

而不是 token 。我敢肯定这很简单,但我在 JS 方面很糟糕。请帮忙!谢谢!

(编辑)我忘了说:

api 身份验证指南链接:https://developer.spotify.com/web-api/authorization-guide/

我卡在了第 4 步。我看到有一种替代方法可以发送“ header 参数”或 cURL 请求,这可能会起作用。但是由于我不知道如何做这些事情,我一直坚持发送 client_id 和 client_secret 作为正文请求参数,就像我之前为用户登录/代码所做的那样。

PS:我只使用我为自己编写的这个应用程序。有没有一种方法可以在不经过此过程的情况下对 token 进行硬编码?

最佳答案

When the authorization code has been received, you will need to exchange it with an access token by making a POST request to the Spotify Accounts service, this time to its /api/token endpoint:

因此您需要向 Spotify API 发出 POST 请求,请求正文中包含参数:

$.ajax(
  {
    method: "POST",
    url: "https://accounts.spotify.com/api/token",
    data: {
      "grant_type":    "authorization_code",
      "code":          code,
      "redirect_uri":  myurl,
      "client_secret": mysecret,
      "client_id":     myid,
    },
    success: function(result) {
      // handle result...
    },
  }
);

(作为旁注,“Unexpected status: 405” 指的是 HTTP 状态代码 405 Method Not Allowed,表示您尝试的请求方法是 GET请求——该 URL 不允许。)

关于javascript - 如何获得访问 token Spotify API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39887342/

相关文章:

html - 有一张不会在某些分辨率下显示的图像

jquery - 使 bootstrap popover 使用自定义 html 模板

javascript - 需要在 GeneXus 中绘制一个 Node-Edges Chart

javascript - 这个 JavaScript 贪吃蛇游戏的错误是什么?

javascript - 使用 jquery 在 ul 菜单中添加 li dynamik

java - 在 Web 服务中传递查询参数之间的区别

php - 使用ajax处理php双数组

javascript - Firebase 在获取查询后运行设置查询

html - 如何对齐 Angular-Material 工具栏中的文本输入?

javascript - 通过在没有 jQuery 全局事件的文本框中输入来调用 JavaScript 函数