首页 文章

在React Native中使用带有Fetch的授权标头

提问于
浏览
83

我正在尝试使用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.stateclientToken 属性设置为等于收到的访问令牌 .

  • 然后,我将运行 getPosts ,它应返回包含Product Hunt当前帖子数组的响应 .

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

我收到的错误如下:

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

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

4 回答

  • 126

    使用授权标头获取示例:

    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'
     });
    
  • 0

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

    fetch 需要两个参数:API的 endpoints 和可以包含正文和 Headers 的可选对象 .

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

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

    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'
      })
    
  • 41

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

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

    我正在运行apache .

    为我解决这个问题的是在 wsgi.conf 中将 WSGIPassAuthorization 更改为 'On' .

    我在AWS EC2上部署了一个Django应用程序,我使用Elastic Beanstalk来管理我的应用程序,所以在_1092083中,我这样做了:

    container_commands:
      01wsgipass:
        command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf'
    
  • -1
    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);
            });
    };
    

相关问题