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

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

问题描述

我正在尝试在 React Native 中使用 fetch 从 Product Hunt API 中获取信息.我已获得正确的访问令牌并将其保存到 State,但似乎无法在 GET 请求的 Authorization 标头中传递它.

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.stateclientToken属性设置为等于收到的访问令牌.
  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 请求.同时请确保您需要正确的范围.例如 "私有公共"用于访问私有端点."}

{"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;
   })

我这样构造我的对象:

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天全站免登陆