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

使用Spotify Web API触发TypeError: callback is not a function问题排查

问题分析与解决方案

你的错误TypeError: callback is not a function来自两处代码问题,并非Spotify API本身的问题:

1. getMe调用方式错误

在/jockey POST路由中,你直接使用await spotifyApi.getMe(),但你使用的spotify-web-api-node版本可能不支持Promise风格调用,该方法必须传入回调函数。当你不传回调时,库会把undefined当作callback参数传入内部,从而触发错误。

同时,调用getMe前你没有给全局的spotifyApi实例设置accessToken,这会导致API请求未授权,即使回调问题解决也会报错。

2. createPlaylistAndAddTracks函数调用参数顺序完全错误

函数定义为:

async function createPlaylistAndAddTracks(userId, playlistName, tracks, accessToken)

但你调用时传入的参数是:

createPlaylistAndAddTracks(userId, request.cookies.access_token, tracks)

参数顺序颠倒,导致playlistName被传入accessToken字符串,accessToken参数缺失为undefined,后续spotifyApi.setAccessToken(accessToken)设置无效token,同时可能引发API调用的参数异常。


修正后的代码示例

修正/jockey POST路由代码

fastify.post("/jockey", async function (request, reply) {
  const prompt = request.body.prompt;
  const promptWithInstruction = `We have a user who wants to listen to music related to the theme: "${prompt}". Can you provide a comma-separated list of keywords or phrases that are relevant to this theme and could be used to search for music on Spotify?`;

  try {
    const result = await openai.createCompletion({
      model: "text-davinci-003",
      prompt: promptWithInstruction,
      max_tokens: 2048,
      temperature: 0.8,
    });

    const generatedText = result.data.choices[0].text.trim();
    const keywords = extractKeywords(generatedText);
    console.log("Generated Keywords:", keywords);
    
    const tracks = await searchAndExtractTracks(keywords, request.cookies.access_token);
    console.log("Extracted tracks:", tracks);
    
    // 给全局spotifyApi实例设置accessToken
    spotifyApi.setAccessToken(request.cookies.access_token);
    // 用Promise包裹getMe调用(适配不支持Promise的库版本)
    const userResponse = await new Promise((resolve, reject) => {
      spotifyApi.getMe((err, data) => {
        if (err) reject(err);
        resolve(data);
      });
    });
    const userId = userResponse.body.id;

    // 生成播放列表名称,修正参数顺序
    const playlistName = `AI Curated: ${prompt}`;
    const playlistId = await createPlaylistAndAddTracks(userId, playlistName, tracks, request.cookies.access_token);

    return reply.redirect("/jockey");

  } catch (error) {
    console.error(error);
    return reply.code(500).send("Error processing request");
  }
});

可选:升级spotify-web-api-node支持Promise

如果将spotify-web-api-node升级到v4.0.0及以上版本,你可以直接使用Promise风格调用,无需手动包裹:

// 设置token后直接await调用
spotifyApi.setAccessToken(request.cookies.access_token);
const userResponse = await spotifyApi.getMe();
const userId = userResponse.body.id;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 19:54:55