3 回答

TA貢獻1865條經驗 獲得超7個贊
我最終做了哪些工作:
async authorize(){
let myHeaders = new Headers();
myHeaders.append("Authorization", `Basic ${my_clientID:clientSecret}`);
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var urlencoded = new URLSearchParams();
urlencoded.append("grant_type", "client_credentials");
const requestOptions = {
method: 'POST',
headers: myHeaders,
body: urlencoded,
redirect: 'follow'
}
let res = await fetch("https://accounts.spotify.com/api/token", requestOptions);
res = await res.json();
return res.access_token;
}
async search(){
const access_token = await this.authorize();
this.setState({access_token});
const BASE_URL = 'https://api.spotify.com/v1/search';
let FETCH_URL = `${BASE_URL}?q=${this.state.query}&type=artist&limit=1`;
const ALBUM_URL = 'https://api.spotify.com/v1/artists';
let myHeaders = new Headers();
myHeaders.append("Authorization", `Bearer ${access_token}`);
const requestOptions = {
method: 'GET',
headers: myHeaders
}
let res = await fetch(FETCH_URL, requestOptions);
res = await res.json();
console.log("ARTIST", res);
}

TA貢獻1828條經驗 獲得超4個贊
從您共享的鏈接中,客戶端憑證流是向 spotify API 服務器發出請求的客戶端(服務器端)。因此,這是一個服務器到服務器的身份驗證流程(不是授權)。您正在使用客戶端的 fecth API,這意味著您的實現應該是服務器端的。如果您使用的是 node.js 運行時服務器端框架,只需查找即可在http.request API
服務器端發出請求。
例如,這將是一個純 node.js 實現:
const options = {
hostname: 'https://accounts.spotify.com/api/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + base64(clientID) + ':' + base64(clientSecret)
}
};
const req = http.request(options, (res) => {
res.setEncoding('utf8');
// process the data bit by bit or in chunks...
res.on('data', (chunk) => {});
// ...and do something with it when there is no more data in response
res.on('end', () => {
console.log('No more data in response.');
});
});
// handle the error explicitly
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
req.end();

TA貢獻1851條經驗 獲得超5個贊
對我來說,我不確定其他人是否也是這種情況,但 spotify api 拒絕base64(clientID) + ":" + base64(clientKey)
,但接受base64(clientID + ":" + clientKey)
添加回答
舉報