Using an authorization header with Fetch in React Native
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'
});
It turns out I was using the fetch
method incorrectly.
fetch
accepts 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', options)
.then(function(res) {
return res.json();
})
.then(function(resJson) {
return resJson;
})
I structured my options object as follows:
var options = {
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'
})
}