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

使用Spotify API获取当前播放曲目遇400错误,请求技术帮助

Spotify API获取当前播放曲目报错400及JSON解析失败解决方法

我正在学习用Spotify API做实验,已经通过用户登录拿到了access token,但调用接口获取当前播放曲目时遇到问题。以下是我的React代码:

import 'bootstrap/dist/css/bootstrap.min.css';
import './App.css';
import {Container, Button } from 'react-bootstrap';
import {useEffect, useState} from 'react';

const CLIENT_ID = process.env.REACT_APP_CLIENT_ID;
const CLIENT_SECRET = process.env.REACT_APP_CLIENT_SECRET;
const REDIRECT_URI = 'http://localhost:3000'
const AUTH_ENDPOINT = 'https://accounts.spotify.com/authorize'
const RESPONSE_TYPE = 'token'

const scopes = ['user-read-currently-playing'];

function App() {
  const [token, setToken] = useState('')
  const [currentTrack, setCurrentTrack] = useState(null)

  useEffect(() => {
    const hash = window.location.hash
    let token = window.localStorage.getItem("token")

    if (!token && hash) {
        token = hash.substring(1).split("&").find(elem => elem.startsWith("access_token")).split("=")[1]

        window.location.hash = ""
        window.localStorage.setItem("token", token)
    }

    setToken(token)
    currentlyPlaying()
  }, [token])

  const logout = () => {
    setToken('')
    window.localStorage.removeItem('token')
  }

  async function currentlyPlaying(){
    var params = {
      method: 'GET',
      headers: {
        'Authorization': 'Bearer ' + token
      }
    }

    var currentPlay = await fetch('https://api.spotify.com/v1/me/player/currently-playing', params)
      .then(response => response.json())
      .then(data => {setCurrentTrack(data)})
  }


  return (
    <div className="App">
      <Container className='d-flex align-items-center justify-content-center' style={{minHeight:'100vh'}}>
          {!token ?
          <Button 
            href={`${AUTH_ENDPOINT}?client_id=${CLIENT_ID}&redirect_uri=${REDIRECT_URI}&response_type=${RESPONSE_TYPE}&scope=${scopes}`} 
            className='btn btn-success'>Login</Button>
          : <Button 
            onClick={logout}
            className='btn btn-danger'>Logout</Button>}

      </Container>
    </div>
  );
}

export default App;

登录重定向后控制台出现如下错误:

App.js:54     GET https://api.spotify.com/v1/me/player/currently-playing 400
currentlyPlaying @ App.js:54
performWorkUntilDeadline @ scheduler.development.js:533
VM766:1 Uncaught (in promise) SyntaxError: Unexpected end of JSON input
    at App.js:54:1
    at async currentlyPlaying (App.js:54:1)

问题原因及修复步骤

1. Scope参数格式错误

Spotify授权接口要求scope参数用空格分隔且需URL编码。你的代码直接拼接数组scopes,虽单个scope看似正常,但不符合官方规范,多scope时会完全失效。修改登录按钮的href:

href={`${AUTH_ENDPOINT}?client_id=${CLIENT_ID}&redirect_uri=${REDIRECT_URI}&response_type=${RESPONSE_TYPE}&scope=${encodeURIComponent(scopes.join(' '))}`}

2. 未处理错误响应

400状态码的响应体通常不是有效JSON,直接调用response.json()会触发解析错误。需先检查响应状态,再处理结果:

async function currentlyPlaying(){
  if (!token) return;

  const params = {
    method: 'GET',
    headers: {
      'Authorization': 'Bearer ' + token
    }
  }

  try {
    const response = await fetch('https://api.spotify.com/v1/me/player/currently-playing', params);
    if (response.status === 204) {
      setCurrentTrack(null); // 用户未播放任何内容时返回204
      return;
    }
    if (!response.ok) {
      console.error('请求失败:', response.status, response.statusText);
      return;
    }
    const data = await response.json();
    setCurrentTrack(data);
  } catch (err) {
    console.error('请求或解析错误:', err);
  }
}

3. 避免无token时调用API

useEffect中token为空时仍会执行currentlyPlaying,导致无效请求。添加token存在判断:

useEffect(() => {
  const hash = window.location.hash
  let token = window.localStorage.getItem("token")

  if (!token && hash) {
      token = hash.substring(1).split("&").find(elem => elem.startsWith("access_token")).split("=")[1]

      window.location.hash = ""
      window.localStorage.setItem("token", token)
  }

  setToken(token);
  if (token) {
    currentlyPlaying();
  }
}, [token])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 01:24:58