首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Spotify Web -为什么新创建的播放列表没有填充所选歌曲?

Spotify Web -为什么新创建的播放列表没有填充所选歌曲?
EN

Stack Overflow用户
提问于 2020-03-18 20:36:41
回答 1查看 782关注 0票数 1

我目前被困在一个反应项目,关于Codecademy干扰。它使用Spotify WEB API创建播放列表并将其保存回用户帐户。

流动情况如下:

  1. 在搜索栏中输入搜索词,
  2. 按搜索按钮通过隐式格兰特流获取临时访问令牌并返回搜索结果,
  3. 搜索结果被填充在结果列表中,
  4. 用户通过将歌曲添加到播放列表列来选择歌曲,
  5. 用户输入所选的播放列表名称并单击Spotify,
  6. 在掩码下,POST方法创建一个具有所选名称的播放列表,并返回唯一id (Spotify.savePlaylist();参见下面),
  7. 唯一的id用于使用另一个POST方法填充所选歌曲的播放列表。

我面临的问题是,当我单击Spotify时,播放列表是在我的帐户中创建的,但是是空的!更重要的是,我得到以下信息:

我将其浓缩为独立代码(从React App.js中删除),以便savePlaylist()函数模拟按钮单击(我成功地再现了问题)。下面的Spotify对象保存了获取访问令牌、搜索歌曲和(我感兴趣的内容)创建播放列表,然后保存各自曲目的方法。

完成API操作的模块Spotify.js如下所示:

代码语言:javascript
复制
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 = 'StackOverflow 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();

另一个小问题(这可能是症状)--当我第一次进行搜索时,将填充轨道列表,然后立即刷新页面。此时,重定向页有一个带有访问令牌的查询字符串,其终止时间如下:

in=3600

只有当我再次搜索这个词时,轨道列表才会被填充。这可能是相关的吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-20 19:11:32

尝试- POST https://api.spotify.com/v1/playlists/{playlist_id}/tracks

而不是- POST https://api.spotify.com/v1/users/{user_id}/playlists/{playlist_id}/tracks

当您在播放列表中添加曲目时。看这个博客帖子

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60747151

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档