【问题标题】:I get the Error code 401 when I run this script, what can I do?运行此脚本时出现错误代码 401,我该怎么办?
【发布时间】:2018-03-20 14:43:08
【问题描述】:

我是编程新手。 我有一个通过蓝牙连接到应用程序的传感器。应用程序将数据发送到云服务。我从云服务中获得了一个链接,其中包含 json 格式的数据。现在我希望这些数据显示在我的网站上,但它的跨域和我所做的任何事情都会显示 401(未经授权)。

<html>
    	<head>
    		<title>Sensor</title>
    		<script src="jquery-3.2.1.min.js"></script>
    	</head>
    		<body>
    	  <h1>Sensor</h1>
    		<button onclick="myFunctionPost()">Start</button>
    		<div id="result" style="color:red"></div>
    		<script>
    			function myFunctionPost() {
    				var getJSON = function(url) {
    					return new Promise(function(resolve, reject) {
    						var xhr = new XMLHttpRequest();
    						xhr.open('get', url, true);
    						xhr.responseType = 'json';
    						xhr.onload = function() {
    							var status = xhr.status;
    							if (status == 200) {
    								resolve(xhr.response);
    							} else {
    								reject(status);
    							}
    						};
    						xhr.send();
    					});
    				};		getJSON('https://thetablewheremydatais$format=json').then(function(data) {
    				alert('Your Json result is:  ' + data.result); //you can comment this, i used it to debug

    				result.innerText = data.result; //display the result in an HTML element
    				}, function(status) { //error detection....
    				alert('Something went wrong.');
    				});
    			}
    		</script>	
    		</body>
    </html>

【问题讨论】:

  • 401 表示您必须进行身份验证。
  • 我知道但我不知道怎么做,我用 client.setRequestHeader("Authorization", "Basic" + btoa("username:password"));
  • 您提到的是基本身份验证,但可能不是服务器所期望的?
  • stackoverflow.com/a/6120260/8744798 这对我有帮助!

标签: javascript json xmlhttprequest cross-domain jsonp


【解决方案1】:

在使用 xhr.send() 调用服务器之前,你有没有试过这行代码

xhr.withCredentials = true;

【讨论】:

  • 不走运
  • @AleksandarK。抱歉,这是我知道的唯一选择,希望其他人仍有解决方案:/
猜你喜欢
  • 2022-11-13
  • 1970-01-01
  • 1970-01-01
  • 2022-11-02
  • 1970-01-01
  • 1970-01-01
  • 2012-06-06
  • 1970-01-01
  • 2021-04-27
相关资源
最近更新 更多