我是编程方面的新手。 我有一个通过bluethooth连接到应用程序的传感器。应用程序将数据发送到云服务。我从包含json格式数据的云服务获取了一个链接。现在我希望将这些数据显示在我的网站上,但是它的跨域和我做的任何事情都说401(未授权)。当我运行这个脚本时,我得到错误代码401,我该怎么办?
<html>
\t <head>
\t \t <title>Sensor</title>
\t \t <script src="jquery-3.2.1.min.js"></script>
\t </head>
\t \t <body>
\t <h1>Sensor</h1>
\t \t <button onclick="myFunctionPost()">Start</button>
\t \t <div id="result" style="color:red"></div>
\t \t <script>
\t \t \t function myFunctionPost() {
\t \t \t \t var getJSON = function(url) {
\t \t \t \t \t return new Promise(function(resolve, reject) {
\t \t \t \t \t \t var xhr = new XMLHttpRequest();
\t \t \t \t \t \t xhr.open('get', url, true);
\t \t \t \t \t \t xhr.responseType = 'json';
\t \t \t \t \t \t xhr.onload = function() {
\t \t \t \t \t \t \t var status = xhr.status;
\t \t \t \t \t \t \t if (status == 200) {
\t \t \t \t \t \t \t \t resolve(xhr.response);
\t \t \t \t \t \t \t } else {
\t \t \t \t \t \t \t \t reject(status);
\t \t \t \t \t \t \t }
\t \t \t \t \t \t };
\t \t \t \t \t \t xhr.send();
\t \t \t \t \t });
\t \t \t \t }; \t \t getJSON('https://thetablewheremydatais$format=json').then(function(data) {
\t \t \t \t alert('Your Json result is: ' + data.result); //you can comment this, i used it to debug
\t \t \t \t result.innerText = data.result; //display the result in an HTML element
\t \t \t \t }, function(status) { //error detection....
\t \t \t \t alert('Something went wrong.');
\t \t \t \t });
\t \t \t }
\t \t </script> \t
\t \t </body>
</html>
'401'意味着你必须进行身份验证。 – sjahan
我知道,但我不知道如何,我试着用client.setRequestHeader(“Authorization”,“Basic”+ btoa(“username:password”)); –
您提到的是基本身份验证,但也许它不是服务器期望的内容? – sjahan