我正在尝试使用React Native中的 fetch
来从Product Hunt API中获取信息 . 我似乎能够在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();
},
我对我的代码的期望如下:
-
首先,我将
fetch
一个访问令牌,其中包含我导入的API模块中的数据 -
之后,我将
this.state
的clientToken
属性设置为等于收到的访问令牌 . -
然后,我将运行
getPosts
,它应返回包含Product Hunt当前帖子数组的响应 .
我能够验证是否正在接收访问令牌,并且 this.state
正在接收它作为 clientToken
属性 . 我也能够验证 getPosts
正在运行 .
我收到的错误如下:
{“error”:“unauthorized_oauth”,“error_description”:“请提供有效的访问令牌 . 请参阅我们的api文档,了解如何授权api请求 . 请确保您需要正确的范围 . 例如\”私人公开\“用于访问私有 endpoints . ”}
我一直在假设我在某种程度上没有在我的授权 Headers 中正确传递访问令牌,但似乎无法弄明白为什么 .
4 回答
使用授权标头获取示例:
事实证明,我错误地使用了
fetch
方法 .fetch
需要两个参数:API的 endpoints 和可以包含正文和 Headers 的可选对象 .我在第二个对象中包装了预期的对象,但没有得到任何想要的结果 .
以下是它在高级别上的表现:
我构建了我的对象:
我有同样的问题,我使用django-rest-knox进行身份验证令牌 . 事实证明,我的fetch方法没有任何问题,如下所示:
我正在运行apache .
为我解决这个问题的是在
wsgi.conf
中将WSGIPassAuthorization
更改为'On'
.我在AWS EC2上部署了一个Django应用程序,我使用Elastic Beanstalk来管理我的应用程序,所以在_1092083中,我这样做了: