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

NextJS使用getServerSideProps时出现XMLHttpRequest未定义错误

解决Next.js SSR中使用spotify-web-api-js报错XMLHttpRequest未定义的问题

错误原因:
spotify-web-api-js是为浏览器环境开发的,底层依赖浏览器提供的XMLHttpRequest对象。而Next.js的getServerSideProps运行在Node.js服务端环境中,Node.js原生没有这个对象,因此会抛出ReferenceError: XMLHttpRequest is not defined。

解决方案

方案1:直接使用Fetch/Axios调用Spotify API(推荐轻量方案)

不需要依赖第三方库,直接用Node.js支持的fetch(Node 18+内置)或axios调用Spotify官方API:

export async function getServerSideProps() {
  const playlistId = "37i9dQZEVXbMDoHDwVN2tF";
  const accessToken = "你的Spotify访问令牌"; // 需提前通过Spotify授权流程获取

  const response = await fetch(
    `https://api.spotify.com/v1/playlists/${playlistId}/tracks?limit=4`,
    {
      headers: {
        Authorization: `Bearer ${accessToken}`
      }
    }
  );

  const playlistData = await response.json();
  const trackList = playlistData.items;

  return { props: { trackList } };
}

方案2:在Node环境中模拟XMLHttpRequest

通过xhr2库在Node.js中模拟浏览器的XMLHttpRequest对象,让spotify-web-api-js可以正常运行:

  1. 安装依赖:
npm install xhr2
  1. 修改getServerSideProps代码:
import xhr2 from 'xhr2';

export async function getServerSideProps() {
  // 全局模拟XMLHttpRequest
  global.XMLHttpRequest = xhr2.XMLHttpRequest;

  const res = await SpotifyApi.getPlaylistTracks("37i9dQZEVXbMDoHDwVN2tF", {
    limit: 4,
  });
  const trackList = res.items;

  return { props: { trackList } };
}

注意:这种方法可能存在兼容性问题,仅作为临时解决方案,不推荐长期使用。

方案3:使用服务端兼容的Spotify SDK(推荐封装方案)

替换为专门支持Node.js环境的Spotify库,比如spotify-api-node:

  1. 安装依赖:
npm install spotify-api-node
  1. 修改代码:
import SpotifyWebApi from 'spotify-api-node';

// 初始化API客户端
const spotifyApi = new SpotifyWebApi({
  clientId: '你的Spotify客户端ID',
  clientSecret: '你的Spotify客户端密钥'
});

export async function getServerSideProps() {
  // 通过客户端凭证流获取访问令牌(适用于无需用户授权的公开数据)
  const credentials = await spotifyApi.clientCredentialsGrant();
  spotifyApi.setAccessToken(credentials.body['access_token']);

  const res = await spotifyApi.getPlaylistTracks("37i9dQZEVXbMDoHDwVN2tF", {
    limit: 4,
  });
  const trackList = res.body.items;

  return { props: { trackList } };
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 07:25:17