首页 > 解决方案 > 为什么在 Codecademy React 项目中未定义 jsonResponse 中的属性“id”?

问题描述

我正处于使用 Spotify API 的 Jammming 项目的最后阶段,试图保存用户播放列表(并在此处练习寻求帮助......谢谢!)。问题代码:Spotify.savePlaylist

let accessToken;
const clientID = 'XXXXX';
const redirectURI = 'http://localhost:3000/';

const Spotify = {
    
    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;
        };
        let accessToken = Spotify.getAccessToken();
        let headers = {Authorization: `Bearer ${accessToken}`};
        let userID;
        return fetch('https://api.spotify.com/v1/me', {headers: headers}
        ).then(response => {
            console.log(response);
            response.json();
        }).then(jsonResponse => {
            userID = jsonResponse.id;
            return fetch(`https://api.spotify.com/v1/user/${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})
                })
            })
        })
    },

    getAccessToken() {
        if (accessToken) {
            return accessToken;
        }

        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]);
            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;
        }
    }
};

export default Spotify;

我得到的错误是:未处理的拒绝(TypeError):无法读取未定义的属性“id”。我的应用程序正在使用隐式授权流,并通过记录来自 API 的响应,我看到:

Response {type: "cors", url: "https://api.spotify.com/v1/me", redirected: false, status: 200, ok: true, …}
body: ReadableStream
locked: true
__proto__: ReadableStream
bodyUsed: true
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: ""
type: "cors"
url: "https://api.spotify.com/v1/me"
__proto__: Response

我很困惑,想知道这个似乎没有授予用户访问权限的响应是否是我调试它的正确轨道。大伙可以给我上一课吗?再次感谢你。

标签: javascriptreactjs

解决方案


错误说的是您尝试从未定义中读取id,而不是id未定义,因此您尝试从中读取 id 的变量jsonResponse是未定义的。

仔细查看您的savePlaylist函数,并注意您没有从响应中返回 json,是什么使链jsonResponse中的下一个then未定义,这就是您尝试id从未定义变量中读取的地方。return之前添加,response.json()然后重试。

什么时候看不到任何id属性的原因console.log response是因为 id 在该响应的正文中,而正文没有在那里显示console.logconsole.log(response.json())可能会产生您正在寻找的解析的 json 响应,并且id会在该对象中。


推荐阅读