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:
- First, I
fetch access token with data from my imported API module. - After that I set the
clientToken property of this.state equal to the access token received. - 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.
Richard Kho May 12 '15 at 11:16 p.m. 2015-05-12 23:16
source share