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

Spotify API返回状态码200但无法获取用户数据求助

问题:Spotify OAuth流程正常但无法获取用户信息

我正在搭建对接Spotify的服务端,目前OAuth流程运行正常:可成功跳转至Spotify登录页面,回调后能获取到access_token、token_type、expires_in、refresh_token和scope参数,/refresh_token接口也可正常工作。但尝试输出用户数据时却无任何内容,尽管响应状态码为200。

代码片段

app.get("/login", (req, res) => {
  const state = generateRandomString(16);
  const scope = "user-read-private user-read-email";

  res.cookie(stateKey, state);

  const usp = new URLSearchParams({
    response_type: "code",
    client_id: CLIENT_ID,
    scope: scope,
    redirect_uri: REDIRECT_URI,
    state: state,
  });
  const uspString = usp.toString();
  console.log(usp);

  res.redirect(`https://accounts.spotify.com/authorize?${uspString}`);
});

app.get("/callback", (req, res) => {
  const code = req.query.code || null;
  const state = req.query.state || null;

  const usp = new URLSearchParams({
    code: code,
    state: state,
    redirect_uri: REDIRECT_URI,
    grant_type: "authorization_code",
  }).toString();

  console.log("Here is the callback");
  axios({
    method: "post",
    url: "https://accounts.spotify.com/api/token",
    data: usp,
    headers: {
      "content-type": "application/x-www-form-urlencoded",
      Authorization: `Basic ${new Buffer.from(
        `${CLIENT_ID}:${CLIENT_SECRET}`
      ).toString("base64")}`,
    },
  })
    .then((response) => {
      console.log(response.data);
      console.log(response.status);
      if (response.status === 200) {
        const { access_token, token_type } = respone.data;
        axios
          .get("https://api.spotify.com/v1", {
            headers: {
              Authorization: `${token_type} ${access_token}`,
            },
          })
          .then((response) => {
            res.send(`<pre>${JSON.stringify(response.data, null, 2)}</pre>`);
          })
          .catch((error) => {
            res.send(error);
          });
      } else {
        res.send(response);
      }
    })
    .catch((error) => {
      res.send(error);
    });
});

app.get("/refresh_token", (req, res) => {
  const { refresh_token } = req.query;
  const usp = new URLSearchParams({
    grant_type: "refresh_token",
    refresh_token: refresh_token,
  }).toString();

  axios({
    method: "post",
    url: "https://accounts.spotify.com/api/token",
    data: usp,
    headers: {
      "content-type": "application/x-www-form-urlencoded",
      Authorization: `Basic ${new Buffer.from(
        `${CLIENT_ID}:${CLIENT_SECRET}`
      ).toString("base64")}`,
    },
  })
    .then((response) => {
      res.send(response.data);
    })
    .catch((error) => {
      res.send(error);
    });
});

问题原因及解决方案

  • API请求地址错误:你当前调用的https://api.spotify.com/v1是Spotify API的根路径,这个接口不会返回用户信息。获取当前授权用户信息的正确接口是https://api.spotify.com/v1/me。
  • 变量拼写错误:代码里const { access_token, token_type } = respone.data;一行中,respone是拼写错误,应该是response。这个错误会导致access_token和token_type变量未定义,后续请求的Authorization头无效,即使状态码返回200,也无法拿到有效数据。
  • 缺少错误日志:内层axios请求的catch块只返回了错误给客户端,没有在控制台打印错误信息,建议加上console.log(error),方便排查问题。

修正后的Callback代码片段

app.get("/callback", (req, res) => {
  const code = req.query.code || null;
  const state = req.query.state || null;

  const usp = new URLSearchParams({
    code: code,
    state: state,
    redirect_uri: REDIRECT_URI,
    grant_type: "authorization_code",
  }).toString();

  console.log("Here is the callback");
  axios({
    method: "post",
    url: "https://accounts.spotify.com/api/token",
    data: usp,
    headers: {
      "content-type": "application/x-www-form-urlencoded",
      Authorization: `Basic ${new Buffer.from(
        `${CLIENT_ID}:${CLIENT_SECRET}`
      ).toString("base64")}`,
    },
  })
    .then((response) => {
      console.log(response.data);
      console.log(response.status);
      if (response.status === 200) {
        // 修正拼写错误
        const { access_token, token_type } = response.data;
        axios
          // 修正API地址
          .get("https://api.spotify.com/v1/me", {
            headers: {
              Authorization: `${token_type} ${access_token}`,
            },
          })
          .then((userResponse) => {
            console.log(userResponse.data); // 添加控制台打印用户数据
            res.send(`<pre>${JSON.stringify(userResponse.data, null, 2)}</pre>`);
          })
          .catch((error) => {
            console.log(error); // 打印错误日志
            res.send(error);
          });
      } else {
        res.send(response);
      }
    })
    .catch((error) => {
      console.log(error); // 打印错误日志
      res.send(error);
    });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 01:24:31