【问题标题】:POST https://accounts.spotify.com/api/token 415 error when using fetch使用 fetch 时 POST https://accounts.spotify.com/api/token 415 错误
【发布时间】:2020-09-30 01:09:30
【问题描述】:

我正在尝试使用 fetch 请求从 spotify api 获取授权代码,但我不断收到 415 错误代码。当我最初使用 $.ajax 而不是 fetch 时,我没有任何错误。

let client_id = '8f10fa8af1aa40c6b52073811460bf33'
let client_secret = '27a7c01912444b409a7f9a6d1f700868'
let ah = btoa(client_id + ":" + client_secret)

const getAuthToken = (searchedTerm) => {
fetch( `https://accounts.spotify.com/api/token`,
  {
    headers: {
      'Content-Type': 'application/x-www-form-url-encoded',
      'Authorization': `Basic ${ah}`
    },
    body: {
      grant_type: 'client_credentials'
    },
    json: true,
    method : "POST"
  }
)

  .then(function(response) { 
    authToken = response.access_token;
    spotifySearch(response.access_token, searchedTerm);  
  })
}

【问题讨论】:

  • 您对该内容类型的信心如何?您是否尝试将其删除或设置为application/json?
  • 是的,我已经尝试将其设置为 application/json,但我仍然得到相同的错误,当我删除它时,我仍然得到相同的错误。

标签: javascript


【解决方案1】:

参见this 类似帖子的回答。请注意,他们在那里设置了'Content-Type':'application/x-www-form-urlencoded',url 和encoded 之间没有连字符。我认为你只需要改变

    headers: {
      'Content-Type': 'application/x-www-form-url-encoded',
      'Authorization': `Basic ${ah}`
    },

到

    headers: {
      'Content-Type': 'application/x-www-form-urlencoded', // no hyphen in urlencoded
      'Authorization': `Basic ${ah}`
    },

【讨论】:

  • 当我取出连字符时,我得到了一个:script.js:43 POST accounts.spotify.com/api/token400 错误。 415 错误不再存在。
  • @JessicaYip - 听起来(希望)一个错误已解决,另一个错误被发现。 Github issue 覆盖 400 秒——对于许多人来说,解决方案似乎是将 Grant Type 作为参数而不是在正文中传递。此外,FWIW,它看起来像 that API is perhaps not intended for consumption in the browser;如果您在浏览器代码中包含可能存在安全问题的客户端密码。
  • 是的,错误正在慢慢显现。现在,我的 Get 请求出现 401 和 405 错误。
猜你喜欢
  • 2016-01-16
  • 2019-05-15
  • 1970-01-01
  • 2017-11-19
  • 2021-07-16
  • 1970-01-01
  • 2020-11-19
  • 1970-01-01
  • 2021-04-27
相关资源
最近更新 更多