所以我尝试使用Spotify API构建一个随机播放列表生成器,当我从他们的服务器获取信息时,它给了我一个401代码。我按照了如何获取访问令牌的教程,现在我已经拥有了它。
我的问题是我现在如何使用此令牌?我再次收到401错误,但我认为这是因为我不知道如何订购网址?
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>
&#13;
我还是js / ajax的新手(这是我的第一个API项目),我一直在关注他们当时没有处理过的教程授权。任何帮助或资源赞赏。感谢。
答案 0 :(得分:1)
访问令牌必须在标题中发送:
卷曲-X GET&#34; https://api.spotify.com/v1/search?q=Muse&type=track,artist&market=US&#34; -H&#34;接受:application / json&#34; -H&#34;授权:Bearer myToken&#34;
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'
}
});