Spotify应用程序请求授权

原学程将引见Spotify运用法式要求受权的处置办法,这篇学程是从其余处所瞅到的,而后减了1些海外法式员的疑问与解问,愿望能对于您有所赞助,佳了,上面开端进修吧。

Spotify应用程序请求授权 教程 第1张

成绩描写

我正在测验考试应用以下代码从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一路应用的三个身份验证流之1。(您不妨全体签出三here)

客户端凭证仅供办事器端应用,不该在前端应用,由于它须要您不该地下的客户端秘密!

您应当改用隐式授与流,它是为在阅读器中应用而树立的。开动以及运转起去也很轻易!

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

// Set token
let _token = hash.access_token;

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

// WordStr 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('%二0')}&response_type=token`;
}

要面:https://gist.github.com/arirawr/f08a一e一七db三a一f六五ada二c一七五九二七五七0四九

这里有1个闭于Gitch的例子,您不妨"Remix"复制并开端制造您的运用法式:https://glitch.com/edit/#!/spotify-implicit-grant

愿望有赞助-乌客快活!??‍?

佳了闭于Spotify运用法式要求受权的学程便到这里便停止了,愿望趣模板源码网找到的这篇技巧文章能赞助到年夜野,更多技巧学程不妨在站内搜刮。