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

调用Spotify API获取Token失败,前端报JSON解析错误求助

问题排查与解决步骤

1. 后端环境变量读取错误

你的server.js里直接写了const clientSecret = secret和const clientId = id,完全没从.env文件读取正确的密钥信息,这会导致Spotify API直接返回400错误。

  • 先在项目根目录创建.env文件,内容如下:
    CLIENT_ID=你的Spotify客户端ID
    CLIENT_SECRET=你的Spotify客户端密钥
    
  • 修改server.js中的变量读取逻辑:
    // 替换原来的clientId和clientSecret定义
    const clientId = process.env.CLIENT_ID;
    const clientSecret = process.env.CLIENT_SECRET;
    
  • 注意:如果.env文件不在根目录,需要给dotenv.config()传入path参数指定文件位置。

2. 后端未正确解析Spotify API响应

你直接把fetch返回的Response对象传给res.json(data),这个对象无法直接序列化为JSON,导致前端解析失败。正确处理方式是先解析Spotify的响应内容:

app.get('/spotify/token', async (req, res) => {
  try {
    const spotifyRes = await fetch('https://accounts.spotify.com/api/token', authParameters);
    // 先解析Spotify返回的响应数据
    const spotifyData = await spotifyRes.json();
    console.log("Spotify响应状态码:", spotifyRes.status);
    console.log("Spotify响应内容:", spotifyData);
    
    // 如果Spotify返回错误,把错误信息原样返回给前端
    if (!spotifyRes.ok) {
      return res.status(spotifyRes.status).json(spotifyData);
    }
    
    res.json(spotifyData);
  } catch (error) {
    console.error('请求Spotify API出错:', error);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

3. 前端请求代理配置缺失

前端运行在http://localhost:5173,后端在http://localhost:3000,直接请求/spotify/token会打到前端服务器而非后端,需要配置代理转发:

  • 如果你用Vite,在vite.config.js中添加代理:
    import { defineConfig } from 'vite';
    import react from '@vitejs/plugin-react';
    
    export default defineConfig({
      plugins: [react()],
      server: {
        proxy: {
          '/spotify': {
            target: 'http://localhost:3000',
            changeOrigin: true,
          },
        },
      },
    });
    
  • 重启前端服务,此时请求/spotify/token会自动转发到后端3000端口。

4. 前端响应解析错误

getToken.js中data.json(data)的写法错误,json()方法不需要传参数,修改为:

const getToken = async () => {
    const res = await fetch('/spotify/token');
    console.log("前端收到的响应:", res);
    // 先检查响应是否正常
    if (!res.ok) {
      throw new Error(`请求失败,状态码: ${res.status}`);
    }
    const result = await res.json();
    console.log("解析后的响应数据:", result);
    return result.access_token;
};

5. 优化Spotify请求参数格式

直接拼接body可能因为特殊字符编码问题导致400错误,建议用URLSearchParams构建请求体:

const authParameters = {
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: new URLSearchParams({
        grant_type: 'client_credentials',
        client_id: clientId,
        client_secret: clientSecret
    })
};

后续排查建议

  • 修改后先直接访问http://localhost:3000/spotify/token,查看返回的具体错误信息(比如invalid_client说明客户端ID/密钥有误)。
  • 确认.env文件没有语法错误,且未被意外提交到版本库中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 17:09:49