Using an Authorization Header with Fetch in React Native

I am trying to use fetch in React Native to get information from the product search API. I got the correct access token and saved it in state, but it seems I couldn’t pass it in the authorization header for the GET request.

Here is what I have so far:

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

The wait that I have for my code is as follows:

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

I can verify that the access token is received and that this.state receives it as a clientToken property. I can also verify that getPosts running.

I get the following error:

{"error": "unauthorized_oauth", "error_description": "Please provide a valid access token. Refer to our api documentation on how to authorize an api request. Also make sure you need the correct areas. For example," public public \ " "to access private endpoints."}

I was working on the assumption that somehow I am passing the access token in my authorization header incorrectly, but it seems I can’t understand exactly why.

+93
javascript react-native fetch-api
May 12 '15 at
source share
4 answers

Turns out I misused the fetch method.

fetch expects two parameters: an API endpoint and an optional object that can contain body and headers.

I wrapped the intended object in the second object, which did not get the desired result.

Here's what it looks like at 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' }) 
+46
May 13 '15 at 2:36
source share

Example of a sample with an authorization header:

 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' }); 
+140
Mar 03 '16 at 18:51
source share

I had the same problem, I used django-rest-knox for authentication tokens. It turns out with my fetch method, which looked like this:

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

I worked Apache.

For me, this problem decided to change WSGIPassAuthorization to 'On' in wsgi.conf .

I had a Django application deployed on AWS EC2 and I used Elastic Beanstalk to control my application, so in django.config I did this:

 container_commands: 01wsgipass: command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf' 
+2
Jun 14 '18 at 20:00
source share
 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); }); }; 
0
Apr 16 '18 at 7:20
source share



All Articles