简体   繁体   English

无法通过XMLHttpRequest验证剩余调用

[英]Unable to authenticate rest call through XMLHttpRequest

I have been using postman to test an API which, I am successfully able to call. 我一直在使用邮递员来测试可以成功调用的API。

When I try to execute this call through javascript I get an authentication error. 当我尝试通过javascript执行此调用时,出现身份验证错误。

The URL and authorization match that of the postman call and when I call using these details with curl I am able to retrieve the correct data. URL和授权与邮递员呼叫的URL和授权匹配,当我使用curl使用这些详细信息进行呼叫时,我能够检索正确的数据。

 <script type="text/javascript">

var data = new FormData();
data.append("attributeId", "");
data.append("validFrom", "");

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.responseText);
  }
});

xhr.open("GET", "http:/restpAPI/test");
xhr.setRequestHeader("authorization", "Basic asdsadsadjlafdkfjkldfj==");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "dsadasd-asdsad-asd-asd-aasd");
xhr.send(data);


  </script>

When I run a local web page with this script I get a 401 saying Unauthorized. 当我使用此脚本运行本地网页时,出现401字样:未经授权。

What is the difference between the JavaScript code and postman or cURL and is there a way of authenticating from JavaScript? JavaScript代码与邮递员或cURL有什么区别,是否可以通过JavaScript进行身份验证?

Update 更新资料

I have discovered that setting the RequestHeader with the authorization key turns the request from a get to an options. 我发现使用授权密钥设置RequestHeader会将请求从获取转换为选项。 This is causing the error. 这导致错误。

尽管HTTP标头应该是不区分大小写的,但您是否尝试过使用标头大小写( Authorization )设置标头的名称?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM