You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js使用Client Credential Flow请求Spotify token返回server_error求助

Spotify Client Credentials Flow 接口报错修复方案

错误根因

该报错与本地localhost运行环境无关,Client Credentials Flow原生支持服务端本地调用。报错是因为请求参数不符合Spotify接口规范:

  • Spotify token接口要求Content-Type请求头必须为application/x-www-form-urlencoded,你的代码错误配置为application/json
  • 请求体需使用URL编码的表单格式,不能使用JSON序列化格式
  • Node.js环境无浏览器端内置的btoa方法,需使用内置Buffer模块实现Base64编码

可正常运行的实现代码

// 提前安装依赖:npm install node-fetch@2
const fetch = require('node-fetch');

const spotifyConfig = {
  clientId: "替换为你的Spotify客户端ID",
  clientSecret: "替换为你的Spotify客户端密钥"
};

const getSpotifyToken = async () => {
  const tokenEndpoint = "https://accounts.spotify.com/api/token";
  const authHeader = `Basic ${Buffer.from(`${spotifyConfig.clientId}:${spotifyConfig.clientSecret}`).toString('base64')}`;

  const response = await fetch(tokenEndpoint, {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      "Authorization": authHeader
    },
    body: "grant_type=client_credentials"
  });

  return await response.json();
};

// 测试调用
getSpotifyToken().then(console.log).catch(console.error);

补充说明

如果你使用axios等其他HTTP客户端,只需保持请求头和请求体格式与上述规范一致即可正常调用。

内容的提问来源于stack exchange,提问作者Mario Perry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 20:18:03