I'm trying to return some data from an API using the Fetch method, but I'm getting a 400 error. I'm probably missing something obvious, but I've been at this for so long I probably can't see the wood for the trees.
<script type="text/javascript">
function getJSON() {
const API = 'https://API-URL-ENDPOINT';
const QUERY = 'sample-query';
const A_KEY = '{API Key}';
const A_SEC = '{API Secret}';
let headers = new Headers();
headers.append('Authorization', 'Basic ' + USERNAME + ":" + PASSWORD);
{/* Fetch Method Here */}
fetch(API, {method: 'GET', headers: headers })
.then(response => response.json())
.then(json => console.log(json));
}
function parseJSON(response) {
return response.json()
}
</script>
If anyone can offer any hints, that would be great.
As written in the docs for the Authorization header, you need to encode it in base64.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization
So try headers.append('Authorization', 'Basic ' + btoa( USERNAME + ":" + PASSWORD ));