Authorization against REST API throws an error: 401 (No credentials found the request.)

Authorization against REST API throws an error: 401 (No credentials found the request.)

我想授权 HP Alm Rest API,我认为这 "should" 有效,但它不:

function performSignIn(){

let headers = new Headers();

headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
headers.append('Authorization', 'Basic ' + base64.encode(username + ":" + password));

fetch(sign_in, {mode: 'no-cors', method:'POST', headers: headers})
  .then(response => response.json())
  .then(json => console.log(json))
  .catch(error => console.log('Authorization failed : ' + error.message));
}

我收到了一些奇怪的错误消息:

401(没有找到请求的凭据。)

这是来自 HP 文档的示例,使用 XMLHttpRequest 完成: http://alm-help.saas.hpe.com/de/12.53/api_refs/REST/webframe.htm#signin-out_example.htm

有什么想法吗?我看不出有什么问题。

非常感谢!

此致, 丹尼尔

fetch(…) 默认情况下不发送凭据。您需要 explicitly specify they should be sent:

fetch(sign_in, {credentials: 'include' , method:'POST', headers: headers})
  .then(response => response.json())
  .then(json => console.log(json))
  .catch(error => console.log('Authorization failed : ' + error.message));
}

此外,顺便说一下,您绝对不想指定 mode: 'no-cors'。其效果是告诉浏览器,阻止我的前端 JavaScript 访问此请求的响应。

谢谢,这似乎有效!但是关于 'no-cors',我收到此错误消息:

对预检请求的响应未通过访问控制检查:请求的资源上不存在 'Access-Control-Allow-Origin' header。因此不允许访问来源“http://127.0.0.1:3000”。响应的 HTTP 状态代码为 501。如果不透明响应满足您的需求,请将请求的模式设置为 'no-cors' 以获取禁用 CORS 的资源。

我以为'no-cors'会有帮助,但实际上没有。