spotify 应用请求授权

spotify application requests authorization

我正在尝试使用以下代码从 spotify 获取 'access token'。

    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));
       }

但是我不断收到错误消息:

    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).

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

来自 Spotify 的 Arielle。

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

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

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

// 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`;
}

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

这里有一个关于 Glitch 的示例,您可以 "Remix" 复制并开始制作您的应用程序:https://glitch.com/edit/#!/spotify-implicit-grant

希望对您有所帮助 - 黑客愉快! ‍

const result = await axios({
  url: this.apiLoginUrl,
  method: 'post',
  data: "grant_type=client_credentials",
  headers: {
    'Authorization': `Basic ${Buffer.from(this.clientId + ":" + this.clientSecret).toString('base64')}`,
  },
});