简体   繁体   中英

Issue with POST Request To Spotify API

I'm working on a web application where you can search the Spotify Library, add songs to a playlist, then add that playlist to your Spotify Account. Everything seems to be working besides saving the Playlist through a POST request to the Spotify API. It gives me a "400 Bad Request" Error. I probably just missed something small, any ideas? The request method:

async savePlaylist(name, trackURIs) {
        if(accessToken === undefined) {
            this.getAccessToken();
        }
        if (name === 'New Playlist' || name === undefined || trackURIs === undefined) {
            return;
        } else {
            let userAccessToken = this.getAccessToken();
            let headers = {Authorization: `Bearer ${userAccessToken}`};
            let userId = await this.findUserId();
            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;
            });
        }
    },

If you need to take a look at the repo for the branch I'm working on, it can be found here .

EDIT: Might need the API Endpoint Documentation

Two things i noticed with your code are:

Authorization: Bearer ${accessToken}

accessToken doesn't seem to be defined anywhere in that block of code rather i see userAccessToken

Second and most likely reason for the error is that the body of your request should be a string(JSON stringified) not an Object

this answers shows a good example

PS: i don't know why anybody voted this down and not give a reason, i hate when that happens

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM