Using an authorization header with Fetch in React Native

前端 未结 4 751
天涯浪人
天涯浪人 2020-11-27 10:18

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 d

4条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 11:20

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

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

提交回复
热议问题