我正在尝试在React Native中使用fetch
从Product Hunt API获取信息。我已经获得了正确的Access Token并将其保存到状态中,但似乎无法在GET请求的Authorization标头中传递它。
目前我有以下代码:
var Products = React.createClass({
getInitialState: function() {
return {
clientToken: false,
loaded: false
}
},
componentWillMount: function () {
fetch(api.token.link, api.token.object)
.then((response) => response.json())
.then((responseData) => {
console.log(responseData);
this.setState({
clientToken: responseData.access_token,
});
})
.then(() => {
this.getPosts();
})
.done();
},
getPosts: function() {
var obj = {
link: 'https://api.producthunt.com/v1/posts',
object: {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + this.state.clientToken,
'Host': 'api.producthunt.com'
}
}
}
fetch(api.posts.link, obj)
.then((response) => response.json())
.then((responseData) => {
console.log(responseData);
})
.done();
},
我对我的代码期望如下:
- 首先,我将使用从我导入的API模块获取的数据
fetch
访问令牌。 - 之后,我将设置
this.state
的clientToken
属性等于所接收到的访问令牌。 - 然后,我将运行
getPosts
,该函数应返回一个包含来自Product Hunt的当前文章数组的响应。
我能够验证访问令牌正在被接收并且this.state
正将其作为它的clientToken
属性。我还可以验证getPosts
正在运行。
我收到的错误信息如下:
{"error":"unauthorized_oauth", "error_description":"Please supply a valid access token. Refer to our api documentation about how to authorize an api request. Please also make sure you require the correct scopes. Eg \"private public\" for to access private endpoints."}
我一直在假设我没有正确地在我的授权标头中传递访问令牌,但似乎无法确定确切原因。
'Authorization': 'Bearer ' + myJWT,
结果发现myJWT被双引号包裹了!Authorization: Bearer "yadda.yadda.yadda"
经过多次尝试解决,我在后端过滤了双引号。 - GuyWrySmile