【发布时间】:2020-09-30 09:35:15
【问题描述】:
我正在尝试在 localhost 上创建一个播放列表,然后将我创建的列表保存到 Spotify。有人可以帮助为什么 保存到 Spotify 按钮可能不起作用?其他一切似乎都很好,我对我使用的获取部分有疑问,但无法弄清楚问题可能是什么。
还有 Spotify.js 代码:
import { SearchBar } from '../components/SearchBar/SearchBar';
const clientId = 'I've put my client id';
const redirectUri = 'http://localhost:3000/callback/';
let accessToken;
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];
let expiresIn = Number(expiresInMatch[1]);
//This clears the parameters, allowing to grab new access token then 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,
artists: 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;
return fetch(`https://api.spotify.com/v1/me`, { headers: headers })
.then((response) => response.json())
.then((jsonResponse) => (userId = jsonResponse.id))
.then((userId) => {
return fetch(`/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(`/v1/users/${userId}/playlists/${playlistId}/tracks`, {
headers: headers,
method: 'POST',
body: JSON.stringify({ uris: trackUris }),
});
});
});
},
};
export default Spotify;
【问题讨论】:
-
您在控制台的网络选项卡中遇到什么错误?
-
刚刚添加,感谢您关注@ludwiguer
-
我看不到任何网络请求,你在哪里调用你的
savePlaylist方法? -
@ludwiguer 在 App.js 文件中,我已将其传递给播放列表组件:
之前仍在 App.js 中我定义了 savePlaylist( ) { 让 trackUris = this.state.playlistTracks.map((track) => track.uri); Spotify.savePlaylist(this.state.playlistName, trackUris).then(() => { this.setState({ playlistName: 'New Playlist', playlistTracks: [] }); }); } -
您能否尝试在您的 fetch 中添加一个 catch 并在控制台中记录错误(如果有)
标签: reactjs fetch spotify access-token