在React Native中使用带有Fetch的授权标头 [英] Using an authorization header with Fetch in React Native

查看:493
本文介绍了在React Native中使用带有Fetch的授权标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use fetch in React Native to grab information from the Product Hunt API. I've obtained the proper Access Token and have saved it to State, but don't seem to be able to pass it along within the Authorization header for a GET request.

以下是我目前的情况:

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. 首先,我将获取包含来自导入的API模块的数据的访问令牌

  2. 之后,我将设置 this.state clientToken 属性以等于访问权限收到令牌。

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

  1. First, I will fetch an access token with data from my imported API module
  2. After that, I will set the clientToken property of this.state to equal the access token received.
  3. Then, I will run getPosts which should return a response containing an array of current posts from Product Hunt.

我能够验证是否正在接收访问令牌以及 this.state 正在接收它作为 clientToken 属性。我还能够验证正在运行 getPosts

I am able to verify that the access token is being received and that this.state is receiving it as its clientToken property. I am also able to verify that getPosts is being run.

我收到的错误如下:


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

{"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."}

我一直在假设我在某种程度上没有在我的授权标题中正确传递访问令牌,但似乎无法弄清楚原因。

I've been working off the assumption that I'm somehow not passing along the access token properly in my authorization header, but don't seem to be able to figure out exactly why.

推荐答案

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

It turns out, I was using the fetch method incorrectly.

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

fetch expects two parameters: an endpoint to the API, and an optional object which can contain body and headers.

我在一秒钟内包装了预期的对象对象,它没有得到任何预期的结果。

I was wrapping the intended object within a second object, which did not get me any desired result.

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

Here's how it looks on a high level:

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

我按原样构建了我的对象:

I structured my object as such:

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

这篇关于在React Native中使用带有Fetch的授权标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆