我尝试使用 Fetch 方法从 API 返回一些数据,但收到 400 错误。我可能错过了一些明显的东西,但我已经从事这个工作太久了,我可能只见树木不见森林。
<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>
如果有人可以提供任何提示,那就太好了。
如授权标头的文档中所述,您需要将其编码为 base64。
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization
所以尝试
headers.append('Authorization', 'Basic ' + btoa( USERNAME + ":" + PASSWORD ));