2016-06-07 62 views
0

我正在使用react-native(并通过使用内置的fetch方法进行本质化操作。我有以下代码可以发布到spotify,并且应该返回一个令牌令牌的我收到一个错误react-native从spotify API获取访问/刷新令牌

代码:

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…} 
+0

您确定您发布的代码为“resCode”是正确的吗? –

回答

0

您发送json海峡在帖子正文中,但是根据文档你必须发送参数。此外,如果你看一下例子卷曲请求你可以看到它是如何做:

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

+0

你知道我该如何编辑我使用fetch发送参数与json字符串? – httpNick

+0

我认为你可以做'var data = new FormData(); data.append('code',resCode);'并且对剩下的参数进行相同操作。根据文档,您可以简单地在请求中传递FormData作为body:'body:data'。 – xjmdoo

+0

尝试后,我得到相同的错误。 – httpNick