【问题标题】:react-native fetching an access/refresh token from spotify APIreact-native 从 spotify API 获取访问/刷新令牌
【发布时间】:2016-06-07 07:55:42
【问题描述】:

我正在使用 react-native(并且本质上使用内置的 fetch 方法。我有以下代码发布到 spotify 并且应该返回一个令牌,而不是我收到错误的令牌。

代码:

  var btoa = require('base-64');      
  var authOptions = {
    method : 'POST',
    body: JSON.stringify({
      code: resCode,
      redirect_uri: 'myapp://foo',
      grant_type: 'authorization_code'
    }),
    headers: {
      'Authorization': 'Basic ' + btoa.encode(secrets.id + ':' + secrets.secret)
    },
    json: true
  };
  fetch('https://accounts.spotify.com/api/token', authOptions).then(
    (res) => console.log(res)
  );

我收到的错误:

Response {_bodyInit: "{"error":"unsupported_grant_type","error_descripti…redentials, authorization_code or refresh_token"}", _bodyText: "{"error":"unsupported_grant_type","error_descripti…redentials, authorization_code or refresh_token"}", type: "default", url: "https://accounts.spotify.com/api/token", status: 400…}

【问题讨论】:

  • 您确定您发布的代码resCode 正确吗?

标签: ios react-native fetch spotify


【解决方案1】:

您在帖子正文中发送json 字符串,但是根据文档,您必须发送参数。此外,如果您查看示例 curl 请求,您可以了解它是如何完成的:

curl -H "Authorization: Basic ZjM...zE=" -d grant_type=authorization_code -d code=MQCbtKe...44KN -d redirect_uri=https%3A%2F%2Fwww.foo.com%2Fauth https://accounts.spotify.com/api/token

不是json。尝试将正文发送为FormData

【讨论】:

  • 你知道如何编辑我使用 fetch 发送参数与 json 字符串的用法吗?
  • 我认为您可以使用var data = new FormData(); data.append('code', resCode); 并对其余参数执行相同操作。根据文档,您可以简单地将 FormData 作为正文传递:body: data 在您的请求中。
猜你喜欢
  • 1970-01-01
  • 2017-06-26
  • 2018-01-08
  • 2021-10-11
  • 1970-01-01
  • 2013-06-14
  • 2017-02-14
  • 1970-01-01
  • 2017-03-22
相关资源
最近更新 更多