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.
Here's 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 expectation I have for my code is the following:
fetch
an access token with data from my imported API moduleclientToken
property of this.state
to equal the access token received.getPosts
which should return a response containing an array of current posts from Product Hunt.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.
The error I'm receiving is the following:
{"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.
Example fetch with 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'
});