如何在VS Code中通过HTTP GET调用Spotify API获取艺人数据
解决Spotify API获取艺人数据问题
问题背景
已完成Spotify开发者账号注册、应用创建,通过官方authorization_code示例代码获取到访问令牌,现需调用「Get Artist」接口获取艺人原始数据,但无法将Spotify提供的HTTP GET命令转化为可执行代码,自行添加的代码无法运行,需要具体实现步骤、所需文件及正确代码写法,在终端输出目标艺人数据。
Spotify「Get Artist」接口信息
GET https://api.spotify.com/v1/artists/{id}
对应的curl命令:
curl -X "GET" "https://api.spotify.com/v1/artists/<my id>" -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer <ACCESS TOKEN>"
目标输出示例
{"external_urls": {"spotify": "https://open.spotify.com/artist/0TnOYISbd1XYRBk9myaseg"},"followers": {"href": null,"total": 9580653},"genres": ["dance pop","miami hip hop","pop","pop rap"],"href": "https://api.spotify.com/v1/artists/0TnOYISbd1XYRBk9myaseg","id": "0TnOYISbd1XYRBk9myaseg","images": [{"height": 640,"url": "https://i.scdn.co/image/ab6761610000e5eb2dc40ac263ef07c16a95af4e","width": 640},{"height": 320,"url": "https://i.scdn.co/image/ab676161000051742dc40ac263ef07c16a95af4e","width": 320},{"height": 160,"url": "https://i.scdn.co/image/ab6761610000f1782dc40ac263ef07c16a95af4e","width": 160}],"name": "Pitbull","popularity": 82,"type": "artist","uri": "spotify:artist:0TnOYISbd1XYRBk9myaseg"}
现有授权代码
/** * This is an example of a basic node.js script that performs * the Authorization Code oAuth2 flow to authenticate against * the Spotify Accounts. * * For more information, read * https://developer.spotify.com/web-api/authorization-guide/#authorization_code_flow */ var express = require('express'); // Express web server framework var request = require('request'); // "Request" library var cors = require('cors'); var querystring = require('querystring'); var cookieParser = require('cookie-parser'); var client_id = '<removed for post>'; // Your client id var client_secret = '<removed for post>'; // Your secret var redirect_uri = 'http://localhost:8888/callback'; // Your redirect uri /** * Generates a random string containing numbers and letters * @param {number} length The length of the string * @return {string} The generated string */ var generateRandomString = function(length) { var text = ''; var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; for (var i = 0; i < length; i++) { text += possible.charAt(Math.floor(Math.random() * possible.length)); } return text; }; var stateKey = 'spotify_auth_state'; var app = express(); app.use(express.static(__dirname + '/public')) .use(cors()) .use(cookieParser()); app.get('/login', function(req, res) { var state = generateRandomString(16); res.cookie(stateKey, state); // your application requests authorization var scope = 'user-read-private user-read-email'; res.redirect('https://accounts.spotify.com/authorize?' + querystring.stringify({ response_type: 'code', client_id: client_id, scope: scope, redirect_uri: redirect_uri, state: state })); }); app.get('/callback', function(req, res) { // your application requests refresh and access tokens // after checking the state parameter /** * URL built up from running node app.js (CONTAINS ACCESS & REFRESH TOKENS!!!): * http://localhost:8888/# * access_token=BQCDky3kGL4j0emQNntiOZsaVBbI5ZkXAfukxmRrjWnAJJGPggVC1hQuEAYhi2nrqKHjt0uVo1MPfOcP_RMdVCCz40TcQArK9vKfxHJplhQRYnl0TZPLDQhYh90ocX3nvnMQzT1kJgUihXnIH-GJ2ZlJ9ol-mwCuh-ro1YrSGhVn2a65kZAYKF5bDjN5-VC2YM2VQAIJmGULsJ-_q77b9Q * &refresh_token=AQDiCPC2Rh0nA0fVg9tCcgY7yUnKz8Zm3G4fUXMVAN5FhIHJpGgFTcFSZ4DAr44ujDMDhygkHw0Us4JnDYJUEMkYIsQaxtgduipF3nDV2JEusZOGC38mssf_W_gzMvzZfNY */ var code = req.query.code || null; var state = req.query.state || null; var storedState = req.cookies ? req.cookies[stateKey] : null; if (state === null || state !== storedState) { res.redirect('/#' + querystring.stringify({ error: 'state_mismatch' })); } else { res.clearCookie(stateKey); var authOptions = { url: 'https://accounts.spotify.com/api/token', form: { code: code, redirect_uri: redirect_uri, grant_type: 'authorization_code' }, headers: { 'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64')) }, json: true }; request.post(authOptions, function(error, response, body) { if (!error && response.statusCode === 200) { var access_token = body.access_token, refresh_token = body.refresh_token; var options = { url: 'https://api.spotify.com/v1/users/31v737d3i7ldefyjefodkxrxalnu', headers: { 'Authorization': 'Bearer ' + access_token }, json: true }; // use the access token to access the Spotify Web API request.get(options, function(error, response, body) { console.log(body); }); // we can also pass the token to the browser to make requests from there res.redirect('/#' + querystring.stringify({ access_token: access_token, refresh_token: refresh_token })); } else { res.redirect('/#' + querystring.stringify({ error: 'invalid_token' })); } }); } }); app.get('/refresh_token', function(req, res) { // requesting access token from refresh token var refresh_token = req.query.refresh_token; var authOptions = { url: 'https://accounts.spotify.com/api/token', headers: { 'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64')) }, form: { grant_type: 'refresh_token', refresh_token: refresh_token }, json: true }; request.post(authOptions, function(error, response, body) { if (!error && response.statusCode === 200) { var access_token = body.access_token; res.send({ 'access_token': access_token }); } }); }); console.log('Listening on 8888'); app.listen(8888);
尝试的错误代码
request.open('GET', 'https://api.spotify.com/v1/artists/{id}', true); request.onload = Function () { var data = JSON.parse(this.response); if (request.status >= 200 && request.status < 400) { var access_token = body.access_token, refresh_token = body.refresh_token; var options = { url: 'https://api.spotify.com/v1/users/<my id>', headers: { 'Authorization': 'Bearer ' + access_token }, json: true }; // use the access token to access the Spotify Web API request.get(options, function(error, response, body) { console.log(body); }); // we can also pass the token to the browser to make requests from there res.redirect('/#' + querystring.stringify({ access_token: access_token, refresh_token: refresh_token })); } else { res.redirect('/#' + querystring.stringify({ error: 'invalid_token' })); } } request.send();
错误原因
这段代码混用了浏览器端XMLHttpRequest的写法(request.open、request.onload)和Node.js环境下request库的用法,逻辑混乱,且未正确结合已获取的访问令牌进行接口调用。
正确实现方案
1. 确认依赖安装
确保已安装项目所需依赖:
npm install express request cors cookie-parser
2. 修改回调逻辑获取艺人数据
在/callback路由的授权成功回调中,替换原有的用户信息请求,改为调用「Get Artist」接口。以下是修改后的关键代码片段:
request.post(authOptions, function(error, response, body) { if (!error && response.statusCode === 200) { var access_token = body.access_token, refresh_token = body.refresh_token; // 替换为你要查询的艺人ID,示例为Pitbull的ID const targetArtistId = '0TnOYISbd1XYRBk9myaseg'; // 配置艺人接口请求参数 var artistOptions = { url: `https://api.spotify.com/v1/artists/${targetArtistId}`, headers: { 'Authorization': 'Bearer ' + access_token }, json: true }; // 调用Get Artist接口并输出结果到终端 request.get(artistOptions, function(error, response, body) { if (!error && response.statusCode === 200) { console.log('=== 目标艺人数据 ==='); console.log(JSON.stringify(body, null, 2)); // 格式化输出,便于阅读 } else { console.error('获取艺人数据失败:', error || body.error); } }); // 保持原有重定向逻辑,将令牌传递到前端(可选) res.redirect('/#' + querystring.stringify({ access_token: access_token, refresh_token: refresh_token })); } else { res.redirect('/#' + querystring.stringify({ error: 'invalid_token' })); } });
3. 完整修改后的代码
将上述片段替换原代码中request.post回调内的对应部分即可,其余代码保持不变。
4. 运行验证
- 在终端执行
node app.js启动服务 - 访问
http://localhost:8888/login完成Spotify授权 - 授权成功后,终端会输出格式化后的艺人数据
内容的提问来源于stack exchange,提问作者anon
相关产品推荐
相关产品推荐

