简体   繁体   中英

How do I use my spotify api token?

So I'm trying to build a random playlist generator using the Spotify API and as I get the info from their server it gives me a 401 code. I followed a tutorial on how to get the access token and now I have it.

My question is how do I use this token now? I've gotten the 401 error again but I think it's because I don't know how to order the url?

JS/html:

 const app = {}; app.apiUrl = 'https://api.spotify.com/v1'; var accessToken = '[private_info]'; //Allow the user to enter some names app.events = function() { $('form').on('submit', function(e) { e.preventDefault(); let artists = $('input[type=search]').val(); artists = artists.split(','); let search = artists.map(artistName => app.searchArtist(artistName)); console.log(search); }); }; //Go to spotify and get the artists app.searchArtist = (artistName) => $.ajax({ url: `${app.apiUrl}/search/` + accessToken, method: 'GET', dataType: 'json', data: { q: artistName, type: 'artist' } }); //With the ids we want to get albums //Then get tracks //Then build playlist app.init = function() { app.events(); }; $(app.init);
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Spotify Playlist Generator</title> <link rel="stylesheet" href="style.css"> </head> <body> <main class="main-container"> <section> <div class="form"> <img src="images/note.svg" alt=""> <form action=""> <input type="search" value=""> <input type="submit" value="Create"> </form> <p>Icon created by unlimicon from the Noun Project</p> </div> <div class="playlist"> <div class="loader"> <div class="inner-circle"></div> </div> </div> </section> </main> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="script.js"></script> </body> </html>

I'm still a bit of a newbie at js/ajax (this is my first API project) and I've been following a tutorial where at the time they didn't have to deal with the authorization. Any help or resources appreciated. Thanks.

The access token must be sent in the headers:

curl -X GET " https://api.spotify.com/v1/search?q=Muse&type=track,artist&market=US " -H "Accept: application/json" -H "Authorization: Bearer myToken"

app.apiUrl = 'https://api.spotify.com/v1';
var accessToken = '[private_info]';

//Go to spotify and get the artists
app.searchArtist = (artistName) => $.ajax({
    url: `${app.apiUrl}/search`,
    headers: {
        'Authorization':'Bearer ' + accessToken
    },
    method: 'GET',
    dataType: 'json',
    data: {
        q: artistName,
        type: 'artist'
    }
});

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