【问题标题】:How to use Express to structure the "Client Credentials Flow" for authorization to use the Spotify API?如何使用 Express 构建“客户端凭据流”以授权使用 Spotify API?
【发布时间】:2021-10-19 20:24:20
【问题描述】:
【问题讨论】:
标签:
node.js
express
axios
spotify
access-token
【解决方案1】:
我想通了,这里对我未来可能会被卡住的朋友提供一些帮助(根据谷歌,我看到很多人被卡住了):
- Axios 是用于向 API 服务器(如 Spotify 的)发出请求的工具。如果您想收听和服务请求,Express 是可以使用的工具。这是为我澄清它的链接:
https://stackoverflow.com/questions/62244076/difference-between-express-js-and-axios-js-in-node#:~:text=Axios%20is%20used%20to%20send,an%20alternative%20to%20fetch().
- 我的目标是使用 Spotify 的客户端凭据流向 Spotify 的 API 服务器发送 POST 请求,并获取允许我使用其 API 的访问令牌。 Axios 有这个实用程序。我还想用 async-await 编写这个函数,以便我的函数在返回之前等待响应。
这是我编写的对我有用的代码:
const axios = require('axios');
const qs = require('qs');
require('dotenv').config();
const client_id = process.env.SPOTIFY_API_ID; // Your client id
const client_secret = process.env.SPOTIFY_CLIENT_SECRET; // Your secret
const auth_token = Buffer.from(`${client_id}:${client_secret}`, 'utf-8').toString('base64');
const getAuth = async () => {
try{
//make post request to SPOTIFY API for access token, sending relavent info
const token_url = 'https://accounts.spotify.com/api/token';
const data = qs.stringify({'grant_type':'client_credentials'});
const response = await axios.post(token_url, data, {
headers: {
'Authorization': `Basic ${auth_token}`,
'Content-Type': 'application/x-www-form-urlencoded'
}
})
//return access token
return response.data.access_token;
//console.log(response.data.access_token);
}catch(error){
//on fail, log the error in console
console.log(error);
}
}
注意:
- 确保在发送之前对授权凭证进行字符串化。不要使用“查询字符串”依赖项。使用较新的 'qs' 依赖项。工作原理相同。
- 使用 'dotenv' 创建 Node.js 环境变量来保护您的敏感数据,就像我做的那样!当您推送到 GitHub 并将 .env 添加到要在 .gitignore 文件中忽略的文件中时,可能会有所帮助!
- Axios 有一些令人困惑的文档,特别是对于像我这样尝试将 API 用于此类身份验证流程的初学者。以下是一些帮助我理解和构建代码的链接(以及大量测试和失败):
https://flaviocopes.com/axios-send-authorization-header/
https://flaviocopes.com/node-axios/