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:
- First, I will
fetch
an access token with data from my imported API module - After that, I will set the
clientToken
property ofthis.state
to equal the access token received. - Then, I will run
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.
'Authorization': 'Bearer ' + myJWT,
Turns out myJWT was getting wrapped in double quotes!Authorization: Bearer "yadda.yadda.yadda"
After many attempts at a solution, I filtered the double quotes on my back-end.