[英]How do I make my PHP API return JSON to a Javascript HTTP POST/GET request?
[英]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>
我的代码中的占位符orgID 、 typeID 、 deviceID 、 logicalInterfaceID等当然已被正确的 ID 替换。
问题是,我不知道如何在 URL 中包含用户名和密码,以便我可以访问 IBM Cloud。
https://www.ibm.com/docs/en/mapms/1_cloud?topic=reference-application-rest-apis
查看这篇关于 cURL 上的 -u 标志实际上在做什么的帖子?
您可以 base64 使用本机btoa() function 对您的凭据进行编码,然后在授权请求 header 中设置它们。
var xhr = new XMLHttpRequest();
xhr.open( "GET", "https://<orgID>...");
xhr.setRequestHeader("Authorization", `Basic ${btoa('username:password')}`);
xhr.send();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.