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

使用Express开发Spotify API时遭遇invalid_client错误排查求助

解决Spotify API获取客户端凭证时的invalid_client错误

你的代码里有个极易忽略的细节错误,直接导致了invalid_client报错:Authorization请求头中"Basic"和base64编码的凭证字符串之间缺少了一个空格。

Spotify的客户端凭证授权要求Authorization头必须严格遵循格式:Basic <base64编码的client_id:client_secret>,没有空格的话服务端无法正确解析你的客户端凭证,自然会返回无效客户端的错误。

核心修正点

把optionsTOKEN里的Authorization头修改为:

headers: {
  "Content-Type": "application/x-www-form-urlencoded",
  "Authorization": "Basic " + code // 注意Basic后面添加空格
},

完整修正后的代码

const express = require("express");
const cors = require("cors");
const fetch = (...args) =>
    import('node-fetch').then(({default: fetch}) => fetch(...args));
  
const request = "https://accounts.spotify.com/api/token";

// 建议用环境变量存储敏感信息,避免硬编码泄露
const client_id = process.env.SPOTIFY_CLIENT_ID;
const client_secret = process.env.SPOTIFY_CLIENT_SECRET;

const code = Buffer.from(`${client_id}:${client_secret}`).toString("base64");

const app = express();
const optionsTOKEN = {
  method: "POST",
  body: "grant_type=client_credentials",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
    "Authorization": "Basic " + code // 关键修正:添加空格
  },
};

app.get("/code", async (req, res) => {
  const data = await retrieveCode(request, optionsTOKEN);
  res.send(data);
});

app.listen(8888, () => {
  console.log("server running on port 8888");
});

async function retrieveCode(URlRequest, options) {
  try {
    const res = await fetch(URlRequest, options);
    const data = await res.json();
    console.log("返回数据:", data);
    return data
  } catch (err) {
    console.error("请求错误:", err);
  }
}

额外检查项

  • 确认client_id和client_secret没有多余的空格、换行符,直接从Spotify开发者控制台复制完整字符
  • 避免硬编码敏感信息,用环境变量(比如process.env)读取更安全
  • 确保请求的Content-Type保持application/x-www-form-urlencoded,你的代码里这部分是正确的

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 20:01:14