簡體   English   中英

從前端 JavaScript 代碼獲取 Spotify API 訪問令牌

[英]Getting Spotify API access token from frontend JavaScript code

我有一個網絡應用程序,它允許人們生成與特定藝術家相關的藝術家的歌曲列表。 我希望能夠連接到用戶的 Spotify 帳戶並從該歌曲列表中為他們創建一個播放列表,但我需要獲取訪問令牌。 我有一個開發者帳戶和客戶 ID,我正在嘗試完成授權流程,但它對我不起作用。 相反,我收到此錯誤: XMLHttpRequest cannot load https://accounts.spotify.com/authorize/?client_id=d137fe25b31c4f3ba9e29d85f…:3000/callback&scope=user-read-private%20user-read-email&state=34fFs29kd09. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. XMLHttpRequest cannot load https://accounts.spotify.com/authorize/?client_id=d137fe25b31c4f3ba9e29d85f…:3000/callback&scope=user-read-private%20user-read-email&state=34fFs29kd09. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

這是我的scripts.js文件的一部分(我使用的是spotify-web-api-js節點模塊):

$('#spotify').on('click', function() {
    $.support.cors = true;
    $.getJSON("https://accounts.spotify.com/authorize/?client_id=d137fe25b31c4f3ba9e29d85f4e47c66&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fcallback&scope=user-read-private%20user-read-email&state=34fFs29kd09", function(json2){
    $.getJSON("https://accounts.spotify.com/api/token/?grant_type=authorization_code&code=" + json2.code + "&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fcallback&client_id=d137fe25b31c4f3ba9e29d85f4e47c66&client_secret={...}", function(json3) {
      s.setAccessToken(json3.access_token);
      });
    });
  });
});

根據我的研究,這是一個與 CORS 相關的問題。 我正在編輯我的 ExpressJS 服務器以解決這個跨域問題並安裝了cors節點模塊,但我仍然遇到同樣的錯誤。

index.js服務器:

var express = require('express');
var cors = require('cors');
var app = express();
var port = 3000;

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});


 app.use(express.static(__dirname + '/public')); // looks in public directory, not root directory (protects files)

 app.get('/', function(req, res) {
     res.send(__dirname + '\\index.html')
});

app.listen(port, function() {
          console.log('CORS-enabled web server listening on port ' + port);
});

當我直接通過瀏覽器訪問有問題的 URL 時,它給了我預期的“您是否授權此應用使用您的 Spotify 信息”表單。

我應該在“scripts.js”中要求“cors”才能工作嗎? 有沒有人有其他建議?

我相信這里的問題是您試圖從應該引導用戶的端點檢索 JSON 數據。 因此,與其向它發出請求,不如在您的頁面上提供一個鏈接到您的https://accounts.spotify.com/authorize/ {...} URL 的按鈕。 用戶將繼續向您的應用程序授予您在scope參數中指定的權限,並將被定向回您在redirect_uri參數中指定的 URL。 這是您獲取授權代碼的地方,您可以在https://accounts.spotify.com/api/token/ {...} 端點中使用該代碼。 授權指南中閱讀有關授權代碼流程的更多信息。

Spotify Web API 支持三種不同的 oAuth 流程,您可能對Implicit Grant感興趣。 https://github.com/spotify/web-api-auth-examples提供了使用 Node 用 Ja​​vascript 編寫的所有這些流程的示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM