Spotify Web API - 为什么新创建的播放列表中没有包含所选歌曲?
Spotify Web API - why is the newly created playlist not populated with chosen songs?
我目前被 Codecademy - Jamming 上的一个 React 项目困住了。它使用 Spotify WEB API 创建播放列表并将其保存回用户帐户。
流程如下:
- 在搜索栏中输入搜索词,
- 按搜索按钮通过隐式授权流程获取临时访问令牌和returns搜索结果,
- 搜索结果填充在结果列表中,
- 用户通过将歌曲添加到播放列表列来选择歌曲,
- 用户输入选择的播放列表名称并点击保存到 Spotify,
- 在幕后,POST 方法使用所选名称和 returns 唯一 ID 创建播放列表(Spotify.savePlaylist();见下文),
- 唯一 ID 用于通过另一种 POST 方法用所选歌曲填充播放列表。
我面临的问题是,当我点击“保存到 Spotify”时,我的帐户中创建了播放列表,但播放列表是空的!最重要的是,我收到以下消息:
我已压缩为独立代码(从 React App.js 中截取)以便通过 savePlaylist() 函数模拟按钮单击(我设法重现了该问题)。下面的 Spotify 对象包含获取访问令牌、搜索歌曲和(我感兴趣的)创建播放列表然后保存相应曲目的方法。
完成API动作的模块Spotify.js如下:
const clientId = '6acd4fb43b3443c190e390753512049d'//Create a working Spotify Web API project to get the client id
const redirectUri = 'https://www.spotify.com/uk/'; //a redirect uri that matches value in the Spotify WEB API project page
let accessToken;
//below are manual entries for the playlist name and tracks (with unique spotify URI)
const playlistTracks = ["spotify:track:6UaHTPaVvS1rasCTUs64N0", "spotify:track:6bC1z4GVrswBEw0D2pOkbT"];
const playlistName = 'Whosebug Jams II';
const Spotify = {
getAccessToken() {
if (accessToken) {
return accessToken;
}
//check for access token match
const accessTokenMatch = window.location.href.match(/access_token=([^&]*)/);
const expiresInMatch = window.location.href.match(/expires_in=([^&]*)/);
if (accessTokenMatch && expiresInMatch) {
accessToken = accessTokenMatch[1];
const expiresIn = Number(expiresInMatch[1]);
// This clears the parameters, allowing us to grab a new access token when it expires
window.setTimeout(() => accessToken = '', expiresIn * 1000);
window.history.pushState('Access Token', null, '/');
return accessToken;
} else {
const accessUrl = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectUri}`;
window.location = accessUrl;
}
},
search(term) {
const accessToken = Spotify.getAccessToken();
return fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`, {
headers: {
Authorization: `Bearer ${accessToken}`
}
}).then(response => {
return response.json();
}).then(jsonResponse => {
if (!jsonResponse.tracks) {
return [];
}
return jsonResponse.tracks.items.map(track => ({
id: track.id,
name: track.name,
artist: track.artists[0].name,
album: track.album.name,
uri: track.uri
}));
})
},
savePlaylist(name, trackUris) {
if (!name || !trackUris.length) {
return;
}
const accessToken = Spotify.getAccessToken();
const headers = { Authorization: `Bearer ${accessToken}` };
let userId;
console.log(trackUris);
console.log(accessToken);
return fetch('https://api.spotify.com/v1/me', { headers: headers }
).then(response => response.json()
).then(jsonResponse => {
userId = jsonResponse.id;
return fetch(`https://api.spotify.com/v1/users/${userId}/playlists`, {
headers: headers,
method: 'POST',
body: JSON.stringify({ name: name })
}).then(response => response.json()
).then(jsonResponse => {
const playlistId = jsonResponse.id;
return fetch(`https://api.spotify.com/v1/users/${userId}/playlists/${playlistId}/tracks`,
{
headers: headers,
method: 'POST',
body: JSON.stringify({ uris: trackUris })
})
})
})
}
};
function savePlaylist() {
Spotify.savePlaylist(playlistName, playlistTracks);
};
savePlaylist();
另一个小问题(可能是一个症状)- 当我第一次进行搜索时,会填充曲目列表,然后立即刷新页面。那时重定向页面有一个查询字符串附加了访问令牌和到期时间,如下所示:
只有当我再次搜索该词时,曲目列表才会出现。这可能相关吗?
尝试 - POST https://api.spotify.com/v1/playlists/{playlist_id}/tracks
而不是 - POST https://api.spotify.com/v1/users/{user_id}/playlists/{playlist_id}/tracks
当您将曲目添加到播放列表时。看到这个 blog post.
我目前被 Codecademy - Jamming 上的一个 React 项目困住了。它使用 Spotify WEB API 创建播放列表并将其保存回用户帐户。
流程如下:
- 在搜索栏中输入搜索词,
- 按搜索按钮通过隐式授权流程获取临时访问令牌和returns搜索结果,
- 搜索结果填充在结果列表中,
- 用户通过将歌曲添加到播放列表列来选择歌曲,
- 用户输入选择的播放列表名称并点击保存到 Spotify,
- 在幕后,POST 方法使用所选名称和 returns 唯一 ID 创建播放列表(Spotify.savePlaylist();见下文),
- 唯一 ID 用于通过另一种 POST 方法用所选歌曲填充播放列表。
我面临的问题是,当我点击“保存到 Spotify”时,我的帐户中创建了播放列表,但播放列表是空的!最重要的是,我收到以下消息:
我已压缩为独立代码(从 React App.js 中截取)以便通过 savePlaylist() 函数模拟按钮单击(我设法重现了该问题)。下面的 Spotify 对象包含获取访问令牌、搜索歌曲和(我感兴趣的)创建播放列表然后保存相应曲目的方法。
完成API动作的模块Spotify.js如下:
const clientId = '6acd4fb43b3443c190e390753512049d'//Create a working Spotify Web API project to get the client id
const redirectUri = 'https://www.spotify.com/uk/'; //a redirect uri that matches value in the Spotify WEB API project page
let accessToken;
//below are manual entries for the playlist name and tracks (with unique spotify URI)
const playlistTracks = ["spotify:track:6UaHTPaVvS1rasCTUs64N0", "spotify:track:6bC1z4GVrswBEw0D2pOkbT"];
const playlistName = 'Whosebug Jams II';
const Spotify = {
getAccessToken() {
if (accessToken) {
return accessToken;
}
//check for access token match
const accessTokenMatch = window.location.href.match(/access_token=([^&]*)/);
const expiresInMatch = window.location.href.match(/expires_in=([^&]*)/);
if (accessTokenMatch && expiresInMatch) {
accessToken = accessTokenMatch[1];
const expiresIn = Number(expiresInMatch[1]);
// This clears the parameters, allowing us to grab a new access token when it expires
window.setTimeout(() => accessToken = '', expiresIn * 1000);
window.history.pushState('Access Token', null, '/');
return accessToken;
} else {
const accessUrl = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectUri}`;
window.location = accessUrl;
}
},
search(term) {
const accessToken = Spotify.getAccessToken();
return fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`, {
headers: {
Authorization: `Bearer ${accessToken}`
}
}).then(response => {
return response.json();
}).then(jsonResponse => {
if (!jsonResponse.tracks) {
return [];
}
return jsonResponse.tracks.items.map(track => ({
id: track.id,
name: track.name,
artist: track.artists[0].name,
album: track.album.name,
uri: track.uri
}));
})
},
savePlaylist(name, trackUris) {
if (!name || !trackUris.length) {
return;
}
const accessToken = Spotify.getAccessToken();
const headers = { Authorization: `Bearer ${accessToken}` };
let userId;
console.log(trackUris);
console.log(accessToken);
return fetch('https://api.spotify.com/v1/me', { headers: headers }
).then(response => response.json()
).then(jsonResponse => {
userId = jsonResponse.id;
return fetch(`https://api.spotify.com/v1/users/${userId}/playlists`, {
headers: headers,
method: 'POST',
body: JSON.stringify({ name: name })
}).then(response => response.json()
).then(jsonResponse => {
const playlistId = jsonResponse.id;
return fetch(`https://api.spotify.com/v1/users/${userId}/playlists/${playlistId}/tracks`,
{
headers: headers,
method: 'POST',
body: JSON.stringify({ uris: trackUris })
})
})
})
}
};
function savePlaylist() {
Spotify.savePlaylist(playlistName, playlistTracks);
};
savePlaylist();
另一个小问题(可能是一个症状)- 当我第一次进行搜索时,会填充曲目列表,然后立即刷新页面。那时重定向页面有一个查询字符串附加了访问令牌和到期时间,如下所示:
只有当我再次搜索该词时,曲目列表才会出现。这可能相关吗?
尝试 - POST https://api.spotify.com/v1/playlists/{playlist_id}/tracks
而不是 - POST https://api.spotify.com/v1/users/{user_id}/playlists/{playlist_id}/tracks
当您将曲目添加到播放列表时。看到这个 blog post.