从前端 JavaScript 代码获取 Spotify API 访问令牌 [英] Getting Spotify API access token from frontend JavaScript code

查看:41
本文介绍了从前端 JavaScript 代码获取 Spotify API 访问令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网络应用程序,允许人们生成与特定艺术家相关的艺术家的歌曲列表.我希望能够连接到用户的 Spotify 帐户并从该歌曲列表中为他们创建一个播放列表,但我需要获取访问令牌.我有一个开发者帐户和客户 ID,我正在尝试通过授权流程,但它对我不起作用.相反,我收到此错误:XMLHttpRequest cannot load https://accounts.spotify.com/authorize/?client_id=d137fe25b31c4f3ba9e29d85f...:3000/callback&scope=user-read-private%20user-read-email&state=34fFs29kd09.请求的资源上不存在Access-Control-Allow-Origin"标头.因此不允许访问源 'http://localhost:3000'.

I have a web app that allows people to generate a list of songs by artists that are related to a particular artist. I want to be able to connect to the user's Spotify account and create a playlist for them from that list of songs, but I need to get an access token. I have a developer account and client ID and am trying to work through the Authorization Flow, but it's not working for me. Instead, I get this error: 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 节点模块):

This is a portion of my scripts.js file (i'm using the spotify-web-api-js node module):

$('#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 节点模块,但我仍然遇到同样的错误.

According to my research, it's a CORS-related issue. I'm making edits to my ExpressJS server to remedy this cross-origin problem and installed the cors node module, but I'm still getting the same error.

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

当我直接通过浏览器转到相关网址时,它会显示预期的您是否授权此应用使用您的 Spotify 信息"表单.

When I go to the URL in question directly through my browser, it gives me the expected "Do you authorize this app to use your Spotify information" form.

我是否需要在scripts.js"中使用cors"才能使其工作?有人有其他建议吗?

Should I require 'cors' in 'scripts.js' for it to work? Does anyone have any other suggestions?

推荐答案

我认为这里的问题是您试图从应该引导用户的端点检索 JSON 数据.因此,与其向它发出请求,您应该在页面上提供一个链接到您的 https://accounts 的按钮.spotify.com/authorize/{...} 网址.用户将继续向您的应用程序授予您在 scope 参数中指定的权限,并将被定向回您在 redirect_uri 中指定的 URL范围.这是您获得授权码的地方,您可以在 https://accounts.spotify.com 中使用它/api/token/{...} 端点.在授权指南.

I believe the issue here is that you're attempting to retrieve JSON data from the endpoint where you should direct your users. So instead of making a request to it, you should supply a button on your page that links to your https://accounts.spotify.com/authorize/{...} URL. The user will proceed to give your application the permissions you've requested as specified in the scope parameter, and will be directed back to the URL you've specified in the redirect_uri parameter. This is where you get the authorization code, which you can use in the https://accounts.spotify.com/api/token/{...} endpoint. Read more about the Authorization Code flow in the Authorization Guide.

Spotify Web API 支持三种不同的 oAuth 流程,您可能对 隐式授权.在 https://github.com 上提供了使用 Node 用 Ja​​vaScript 编写的所有这些流程的示例/spotify/web-api-auth-examples.

Spotify Web API support three different oAuth flows, and you might be interested in Implicit Grant. Examples of all of these flows written in Javascript using Node is available at https://github.com/spotify/web-api-auth-examples.

这篇关于从前端 JavaScript 代码获取 Spotify API 访问令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆