如何使用 JavaScript 通过 HTTP 请求从 IBM Cloud 获取 JSON 格式的数据?

How do I get data as JSON format from the IBM Cloud with a HTTP Request using JavaScript?

当我在我的应用程序中单击“获取数据”时,我想通过 HTTP 请求访问我的 IBM Cloud 中的数据。我需要 JSON 格式的数据。这应该用 JavaScript 来实现。 我当前的代码在这里:

function httpRequest() {
  const xhr = new XMLHttpRequest()
//open a get request with the remote server URL
xhr.open("GET", "https://<orgID>.internetofthings.ibmcloud.com/api/v0002/device/types/<typeID>/devices/<deviceID>/state/<logicalInterfaceID>" )
//send the Http request
xhr.send()

//EVENT HANDLERS

//triggered when the response is completed
xhr.onload = function() {
  if (xhr.status === 200) {
    //parse JSON datax`x
    data = JSON.parse(xhr.responseText)
    console.log(data.count)
    console.log(data.products)
  } else if (xhr.status === 404) {
    console.log("No records found")
  }
}

//triggered when a network-level error occurs with the request
xhr.onerror = function() {
  console.log("Network error occurred")
}

//triggered periodically as the client receives data
//used to monitor the progress of the request
xhr.onprogress = function(e) {
  if (e.lengthComputable) {
    console.log(`${e.loaded} B of ${e.total} B loaded!`)
  } else {
    console.log(`${e.loaded} B loaded!`)
  }
}
}
.btn {
  cursor: pointer;
  background-color: #555;
  color: #fff;
  display: inline-block;
  padding: 5px;
  margin-left: auto;
  margin-right: auto;
}
<!DOCTYPE html>
<html lang="de">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="src/css/styles.css"/>
    <script src="src/js/script.js"></script>
    <title>GET DATA</title>
    <div class="btn" onclick="httpRequest()">
      GET DATA
    </div>   
  </head>
  <body>
  </body>
</html>

占位符orgIDtypeIDdeviceIDlogicalInterfaceID 在我的代码等中当然已被正确的 ID 替换。

问题是,我不知道如何在 URL 中包含用户名和密码,以便我可以访问 IBM Cloud。

https://www.ibm.com/docs/en/mapms/1_cloud?topic=reference-application-rest-apis

What is -u flag on cURL actually doing?

上查看此 post

您可以使用本机 btoa() 函数对凭据进行 base64 编码,然后在授权请求中设置它们 header。

var xhr = new XMLHttpRequest();
xhr.open( "GET", "https://<orgID>...");
xhr.setRequestHeader("Authorization", `Basic ${btoa('username:password')}`);    
xhr.send();