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

Time:12-12

When I click on "GET DATA" in my App, I would like to access the data in my IBM Cloud with an HTTP request. I need the data in JSON format. This should be implemented with JavaScript. My current code is here:

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  onclick="httpRequest()">
      GET DATA
    </div>   
  </head>
  <body>
  </body>
</html>

The placeholder orgID, typeID, deviceID, logicalInterfaceID in my code etc. have of course been replaced by the correct ID.

The problem is, I don't know how to include the username and password in the URL so that I can access the IBM Cloud.

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

CodePudding user response:

Checkout this post on What is -u flag on cURL actually doing?

You can base64 encode your credentials using the native btoa() function then set them in the authorization req header.

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