Spotify 应用程序请求授权

mei*_*sam 4 api ajax spotify access-token web

我正在尝试使用以下代码从 Spotify 获取“访问令牌”。

    var encoded = btoa(client_id+':'+client_secret);
    function myOnClick() {
       console.log('clikced!');
       $.ajax({
       url: 'https://accounts.spotify.com/api/token',
       type: 'POST',
       data: {
            grant_type : "client_credentials",
           'Content-Type' : 'application/x-www-form-urlencoded'
       },
       headers: {
           Authorization: 'Basic ' + encoded
       },
       dataType: 'json'
       }).always((data)=> console.log(data));
       }
Run Code Online (Sandbox Code Playgroud)

但是我不断收到错误:

    Cross-Origin Request Blocked: The Same Origin Policy disallows reading
    the remote resource at https://accounts.spotify.com/api/token.
    (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Run Code Online (Sandbox Code Playgroud)

和就绪状态:0,状态:0

小智 5

来自 Spotify 的 Arielle 在这里。

看起来您正在使用客户端凭据流,这是您可以与 Spotify API 一起使用的 3 个身份验证流之一。(您可以在此处查看所有 3 个)

Client Credentials 仅供服务器端使用,不应在前端使用,因为它需要您不应公开的客户端机密!

您应该使用隐式授权流程,该流程专为在浏览器中使用而设计。启动和运行也很容易!

// Get the hash of the url
const hash = window.location.hash
.substring(1)
.split('&')
.reduce(function (initial, item) {
  if (item) {
    var parts = item.split('=');
    initial[parts[0]] = decodeURIComponent(parts[1]);
  }
  return initial;
}, {});
window.location.hash = '';

// Set token
let _token = hash.access_token;

const authEndpoint = 'https://accounts.spotify.com/authorize';

// Replace with your app's client ID, redirect URI and desired scopes
const clientId = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
const redirectUri = 'http://localhost:8888';
const scopes = [
  'user-read-birthdate',
  'user-read-email',
  'user-read-private'
];

// If there is no token, redirect to Spotify authorization
if (!_token) {
  window.location = `${authEndpoint}?client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scopes.join('%20')}&response_type=token`;
}
Run Code Online (Sandbox Code Playgroud)

要点:https : //gist.github.com/arirawr/f08a1e17db3a1f65ada2c17592757049

这里有一个关于 Glitch 的例子,你可以“混音”来制作副本并开始制作你的应用程序:https ://glitch.com/edit/#!/spotify-implicit-grant

希望有所帮助 - 快乐黑客!?