【问题标题】:Spotify Web API returns 404 with valid show idSpotify Web API 返回 404 并带有有效的节目 ID
【发布时间】:2022-01-12 23:57:51
【问题描述】:

我正在试用 WebAPI,但遇到了一个没有意义的问题。

在开发者控制台中搜索节目 ID 4rOoJ6Egrf8K2IrywzwOMk 的剧集列表会返回一个列表。

如果我登录到我的 spotify 帐户,即使在浏览器中访问给定的 URL (https://api.spotify.com/v1/shows/4rOoJ6Egrf8K2IrywzwOMk/episodes) 也会返回剧集列表。

我不确定我的代码出了什么问题。

async function listPodcastEpisodes(id) {
  const access_token = await getAuth()
  const api_url = `https://api.spotify.com/v1/shows/${id}/episodes`
  console.log(api_url)
  try {
    const response = await axios.get(api_url, setAxiosOptions(access_token))
    return response.data
  } catch(err) {
    console.log(`Error: ${JSON.stringify(err?.response?.data, null, 2)}`)
  }
}

listPodcastEpisodes(process.argv[2])
  .then(x => console.log(x))

此代码返回:

$ node getInfo.js 4rOoJ6Egrf8K2IrywzwOMk
https://api.spotify.com/v1/shows/4rOoJ6Egrf8K2IrywzwOMk/episodes
Error: {
  "error": {
    "status": 404,
    "message": "non existing id"
  }
}
undefined

其他功能和变量设置:

const auth = `${process.env.ID}:${process.env.SECRET}`
const auth_encoded = Buffer.from(auth, 'utf-8').toString("base64")

function setAxiosOptions(data) {
  return {
    headers: {
      'Authorization': `Bearer ${data}`,
      'Content-Type': 'application/json'
    }
  }
}

async function getAuth () {
  try {
    const token_url = 'https://accounts.spotify.com/api/token';
    const data = qs.stringify({'grant_type':'client_credentials'});
    const response = await axios.post(token_url, data, {
      headers: { 
        'Authorization': `Basic ${auth_encoded}`,
        'Content-Type': 'application/x-www-form-urlencoded' 
      }
    })

    return response.data.access_token;
  } catch(error) {
    console.log(error);
  }
}

【问题讨论】:

  • 可能不相关,但 GET 请求不需要内容类型标头,因为它们没有请求正文。我唯一要做的另一件事是对 ID 进行 URL 编码,例如 `https://api.spotify.com/v1/shows/${encodeURIComponent(id)}/episodes`
  • 是的,这是关于内容类型标题的一个好点。没有必要对 id 进行编码,它是纯粹的字母数字。
  • 既然是命令行参数,你永远不能太确定
  • 它没有改变任何东西。

标签: javascript node.js spotify


【解决方案1】:

您可能需要包含market 参数。

我在官方 Web API 存储库中找到了这个 GitHub issue,描述了您遇到的相同问题。 this issue 引用了这个问题,GitHub 用户 MrXyfir 在这里发帖 their workaround

编辑:对于遇到此问题的其他任何人,我的解决方案是设置市场参数。 https://api.spotify.com/v1/shows/4rOoJ6Egrf8K2IrywzwOMk/episodes?market=US

【讨论】:

  • 我之前看到过这个,并没有适当地考虑它。这次我仔细查看了我的代码并能够修复它。谢谢你的建议。它让我看得更近,我能够让它工作。 “市场”查询似乎很关键。当我将代码添加到我的搜索网址时,代码返回了预期的数据。
猜你喜欢
  • 2012-06-22
  • 2021-01-15
  • 2017-07-21
  • 1970-01-01
  • 2014-05-07
  • 1970-01-01
  • 2016-09-13
  • 2023-02-15
  • 1970-01-01
相关资源
最近更新 更多