Spotify/axios 我的第一个个人项目的问题(菜鸟问题)

Spotify/axios question for my first solo project (noob question)

这可能是一个愚蠢的问题 - 我在 9 月份才开始学习代码,这是我在 React 中的第一个独立项目(或者根本不是真的)。​​

我在尝试向 Spotify API 发出 POST 请求以取回访问令牌时在我的第一个构建中遇到了困难:

https://developer.spotify.com/documentation/general/guides/authorization/client-credentials/

我不断收到此请求的错误 415,我正在使用 'Content-Type':'application/x-www-form-urlencoded',因为他们在 Spotify API 文档中推荐。

如有任何帮助,我们将不胜感激!

export const SpotifyAPI = () => {

const buffer = new Buffer.from(`${client_id}:${client_secret}`);

  axios.post(
    'https://accounts.spotify.com/api/token', {
        form: { grant_type: 'client_credentials' },
        headers: {
            Authorization: 'Basic' + buffer.toString('base64'),
            'Content-Type': 'application/x-www-form-urlencoded',
        },
    }).then(response => console.log(response));

Axios 没有 form 选项。请求的主体进入 data 参数。如果你想要 URL 编码数据,你必须将数据转换为字符串,你不能只传递一个对象。

这里有一个 HOWTO in the axios documentation


this is my first solo project in React

在浏览器中一般 运行s client-side 反应。您 link 的文档说:

The Client Credentials flow is used in server-to-server authentication.

它不适用于浏览器中的用户,尝试这样做可能会 运行 导致 CORS 错误并将您的客户端机密泄露给您网站的每个访问者。