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

Spotify Web Playback SDK转播放出现404错误但功能正常求助

Spotify Web Playback SDK 转移播放时出现404错误但功能正常

背景信息

通过Authorization code with PKCE流程对接Spotify Web API/Playback功能,已完成授权(配置对应scopes),获取了access_token和refresh_token,多个API(如Get Available Devices、Get Track等)均可正常调用。

问题描述

尝试将播放转移到Web应用创建的Web播放器时,控制台出现404错误:

POST https://cpapi.spotify.com/v1/client/170e8fd3f7fe5ed17f77f8939c19664dcfabd80b/event/item_before_load 404

检查Web Playback SDK初始化和播放转移函数后发现,设置转移后立即播放时歌曲可正常播放(Spotify客户端也显示Web播放器正在播放),但仍会出现上述404错误。测试转移到其他设备(桌面、手机客户端)时,功能正常且无错误。已验证相关变量存储正确,更换设备ID调用transferPlayback也成功,仅Web播放器转移时报错但功能正常。

代码片段

DappMyMusicContext.jsx

const transferPlayback = async (curDeviceId) => {
  const token = getAccessToken; //Access token received from auth
  if (player) {
    await player.activateElement();
  }
  const response = await fetch("https://api.spotify.com/v1/me/player", {
    method: "PUT",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify({
      device_ids: [curDeviceId],
      play: true,
    }),
  });

  const data = await response;
  console.log(data);
};
useEffect(() => {
  if (!getAccessToken) return;
  const script = document.createElement("script");
  script.src = "https://sdk.scdn.co/spotify-player.js";
  script.async = true;

  document.body.appendChild(script);

  window.onSpotifyWebPlaybackSDKReady = () => {
    const player = new window.Spotify.Player({
      name: "DappMyMusicWebPlayer",
      getOAuthToken: (cb) => {
        cb(getAccessToken);
      },
      volume: 0.5,
    });

    setPlayer(player);

    player.addListener("ready", ({ device_id }) => {
      console.log("Ready with Device ID", device_id);
      setDeviceId(device_id);
      setIsPlayerReady(true);
    });

    player.addListener("not_ready", ({ device_id }) => {
      console.log("Device ID has gone offline", device_id);
      setIsPlayerReady(false);
    });

    player.addListener("initialization_error", ({ message }) => {
      console.error("Initialization Error:", message);
    });

    player.addListener("authentication_error", ({ message }) => {
      console.error("Authentication Error:", message);
    });

    player.addListener("account_error", ({ message }) => {
      console.error("Account Error:", message);
    });

    player.addListener("playback_error", ({ message }) => {
      console.error("Playback Error:", message);
    });

    player.connect();
    console.log(player);
  };
}, [getAccessToken]);

WebPlaybackComponent.jsx

import React, { useState, useEffect, useContext } from "react";
import { DappMyMusicContext } from "../context/DappMyMusicContext";

const WebPlayback = () => {
  const { getAccessToken, transferPlayback, isPlayerReady, deviceId } =
    useContext(DappMyMusicContext);
  console.log("isPlayerReady: " + isPlayerReady + "\ndeviceId: " + deviceId);
  const checkDevices = async () => {
    const token = localStorage.getItem("access_token");

    const response = await fetch(
      "https://api.spotify.com/v1/me/player/devices",
      {
        method: "GET",
        headers: {
          Authorization: `Bearer ${token}`,
        },
      }
    );

    const data = await response.json();
    console.log("🎵 Available Devices:", data);
  };

  const checkCurrentDevice = async () => {
    const token = localStorage.getItem("access_token");

    const response = await fetch("https://api.spotify.com/v1/me/player", {
      method: "GET",
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });

    const data = await response;
    console.log("Current playback device:", data);
  };

  return (
    <>
      <div className="container">
        <div className="main-wrapper">
          <button type="button" onClick={() => transferPlayback(deviceId)}>
            Play
          </button>
        </div>
        <div>
          <button type="button" onClick={checkDevices}>
            List of Devices
          </button>
        </div>
        <div>
          <button type="button" onClick={checkCurrentDevice}>
            Current Device
          </button>
        </div>
      </div>
    </>
  );
};

export default WebPlayback;

补充信息

响应头

access-control-allow-origin: https://sdk.scdn.co
alt-svc: h3=":443"; ma=2592000,h3-29=":443"; ma=2592000
content-length: 0
date: Mon, 10 Mar 2025 00:10:25 GMT
server: envoy
strict-transport-security: max-age=31536000
via: HTTP/2 edgeproxy, 1.1 google
x-content-type-options: nosniff

请求头

:authority: cpapi.spotify.com
:method: POST
:path: /v1/client/ec07d32246509182d6dca86f02216fa60493f604/event/item_before_load
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br, zstd
accept-language: en-US,en;q=0.9
authorization: Bearer BQDZhyBlZVpbTsNgKc2WrjOdZpzR3Bvlc-yu7RE7CFHah_sYXTWWQsFe8IBEQWjF3SMvchztULqlv2rn888JKJ1D1gchr-RJcML3VZmFhWMQgbJutOOUNN-9I_oociiBTbI6Pw5mCdqKWmgxunFqfI1I26uACp4ZIG_mjxfGQpzl697VVV4iIPuRtGEd2PZx3KokbCJGpZQiRVghBZtWENoCBR4gfmAaU4v6rWdLQyPnhVw
content-length: 288
content-type: application/json
origin: https://sdk.scdn.co
priority: u=1, i
referer: https://sdk.scdn.co/
sec-ch-ua: "Not(A:Brand";v="99", "Google Chrome";v="133", "Chromium";v="133"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36

已尝试多种实现方式,搜索类似错误但未找到有效解决方案。


解决方案

这个404错误是Spotify Web Playback SDK内部的请求失败,和你的代码逻辑无关,不会影响播放功能正常运行。

原因

cpapi.spotify.com是Spotify内部用于事件上报、统计的服务,SDK会自动发起这类请求,但部分端点可能存在临时下线或路由配置问题,属于Spotify侧的故障,不是你的代码问题。

处理方式

  1. 直接忽略该错误,因为它不干扰核心播放功能;
  2. 若不想被控制台报错干扰,可添加全局fetch拦截过滤该错误:
const originalFetch = window.fetch;
window.fetch = async (...args) => {
  const response = await originalFetch(...args);
  if (args[0].includes('cpapi.spotify.com') && response.status === 404) {
    // 过滤该域名的404错误,不输出到控制台
    return response;
  }
  return response;
};
  1. 等待Spotify自行修复内部端点问题,这类临时错误通常会在短时间内恢复。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 01:15:00