【发布时间】:2018-01-30 19:28:01
【问题描述】:
我正在开发一个与 Spotify API 配合使用的项目,以允许用户搜索歌曲/播放列表并将其添加到他们的帐户中。我正在对它进行全部编码,并且我达到了没有编译器错误的地步,唯一的错误是:
警告:数组或迭代器中的每个子元素都应该有一个唯一的“key”属性。
但应用程序似乎没有任何功能,您无法将歌曲添加到播放列表、搜索播放列表等。我正在尝试确定我的 API 模块是否有问题,因为这是我唯一能做的认为这有问题并且不会引发任何错误。该模块如下所示,或者您可以查看repo 这是我们被告知要使用的Spotify API Authorization Document
function Spotify() {
function getAccessToken() {
if(accessToken !== '') {
return accessToken;
} else if (window.location.href.match(/access_token=([^&]*)/) != null){
accessToken = window.location.href.match(/access_token=([^&]*)/);
expiresIn = window.location.href.match(/expires_in=([^&]*)/);
window.setTimeout(() => accessToken = '', expiresIn * 1000);
window.history.pushState('Access Token', null, '/');
} else {
window.location = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&scope=playlist-modify-public&redirect_uri=${redirectURI}`;
}
async function search(term) {
accessToken=getAccessToken();
try {
let response = await fetch(`https://api.spotify.com/v1/search?type=track&q=${term}`, {
method: 'GET',
headers: {
Authorization: `Bearer ${accessToken}`
}
});
if (response.ok) {
let jsonResponse = await response.json();
let tracks = jsonResponse.map(track => ({
id: track.id,
name: track.name,
artist: track.artists[0].name,
album: track.album.name,
uri: track.uri
}));
return tracks;
}
} catch (error) {
console.log(error);
}
}
function savePlaylist(name, trackURIs) {
if (name === undefined || trackURIs === undefined) {
return;
} else {
let userAccessToken = getAccessToken();
let headers = {Authorization: userAccessToken};
let userId = findUserId(headers);
let playlistID;
fetch(`https://api.spotify.com/v1/users/${userId}/playlists`, {
method: 'POST',
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": 'application/json'
},
body: {
name: name
}
}).then(response => {return response.json()}
).then(playlist => {
playlistID = playlist.id;
});
}
}
function findUserId(headers) {
accessToken = getAccessToken();
let id;
fetch(`https://api.spotify.com/v1/me`, {headers: headers}
).then(response => {return response.json()}
).then(jsonResponse => {
id = jsonResponse[0].id;
});
return id;
}
}
}
export default Spotify;
【问题讨论】:
标签: javascript reactjs spotify