使用React Native中的Fetch授权标头

问题描述 投票:95回答:4

我正在尝试使用React Native中的fetch从Product Hunt API中获取信息。我已经获得了正确的访问令牌并将其保存到状态,但似乎无法在GTP请求的授权标头内传递它。

这是我到目前为止所拥有的:

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();
  },

我对我的代码的期望如下:

  1. 首先,我将fetch一个访问令牌,其中包含我导入的API模块中的数据
  2. 之后,我将clientTokenthis.state属性设置为等于收到的访问令牌。
  3. 然后,我将运行getPosts,它应该返回一个包含Product Hunt当前帖子数组的响应。

我能够验证是否正在接收访问令牌,并且this.state正在接收它作为其clientToken属性。我也能够验证getPosts正在运行。

我收到的错误如下:

{“error”:“unauthorized_oauth”,“error_description”:“请提供有效的访问令牌。请参阅我们的API文档,了解如何授权api请求。请确保您需要正确的范围。例如,”私人公共\ “用于访问私有端点。”}

我一直在假设我在某种程度上没有在我的授权标题中正确传递访问令牌,但似乎无法弄明白为什么。

javascript oauth-2.0 react-native fetch-api
4个回答
141
投票

使用授权标头获取示例:

fetch('URL_GOES_HERE', { 
   method: 'post', 
   headers: new Headers({
     'Authorization': 'Basic '+btoa('username:password'), 
     'Content-Type': 'application/x-www-form-urlencoded'
   }), 
   body: 'A=1&B=2'
 });

47
投票

事实证明,我错误地使用了fetch方法。

fetch需要两个参数:API的端点,以及可以包含正文和标题的可选对象。

我在第二个对象中包装了预期的对象,但没有得到任何想要的结果。

以下是它在高级别上的表现:

fetch('API_ENDPOINT', OBJECT)  
  .then(function(res) {
    return res.json();
   })
  .then(function(resJson) {
    return resJson;
   })

我构建了我的对象:

var obj = {  
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Origin': '',
    'Host': 'api.producthunt.com'
  },
  body: JSON.stringify({
    'client_id': '(API KEY)',
    'client_secret': '(API SECRET)',
    'grant_type': 'client_credentials'
  })

3
投票

我有同样的问题,我使用django-rest-knox进行身份验证令牌。事实证明,我的fetch方法没有任何问题,如下所示:

...
    let headers = {"Content-Type": "application/json"};
    if (token) {
      headers["Authorization"] = `Token ${token}`;
    }
    return fetch("/api/instruments/", {headers,})
      .then(res => {
...

我正在运行apache。

为我解决这个问题的原因是在WSGIPassAuthorization'On'改为wsgi.conf

我在AWS EC2上部署了一个Django应用程序,我使用Elastic Beanstalk来管理我的应用程序,因此在django.config中,我这样做了:

container_commands:
  01wsgipass:
    command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf'

0
投票
completed = (id) => {
    var details = {
        'id': id,

    };

    var formBody = [];
    for (var property in details) {
        var encodedKey = encodeURIComponent(property);
        var encodedValue = encodeURIComponent(details[property]);
        formBody.push(encodedKey + "=" + encodedValue);
    }
    formBody = formBody.join("&");

    fetch(markcompleted, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: formBody
    })
        .then((response) => response.json())
        .then((responseJson) => {
            console.log(responseJson, 'res JSON');
            if (responseJson.status == "success") {
                console.log(this.state);
                alert("your todolist is completed!!");
            }
        })
        .catch((error) => {
            console.error(error);
        });
};
© www.soinside.com 2019 - 2024. All rights reserved.