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

自作多情 提交于 2021-01-28 04:43:22

问题


I want to authorize against the HP Alm Rest API, I think this "should" work, but it does not:

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));
}

I get a bit weird error message:

401 (No credentials found the request.)

This is an example from the HP documentation, done with XMLHttpRequest: http://alm-help.saas.hpe.com/de/12.53/api_refs/REST/webframe.htm#signin-out_example.htm

Any idea? I don't see what's wrong.

Thank's a lot!

Best regards, Daniel


回答1:


fetch(…) by default doesn’t send credentials. You need to 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));
}

Also, incidentally, you definitely don’t want to specify mode: 'no-cors'. The effect that has is to tell the browser, Block my frontend JavaScript from accessing the response from this request.




回答2:


Thank you, that seems to work! But regarding 'no-cors', I get this error message:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:3000' is therefore not allowed access. The response had HTTP status code 501. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I thought 'no-cors' will help, but actually it does not.



来源:https://stackoverflow.com/questions/43866258/authorization-against-rest-api-throws-an-error-401-no-credentials-found-the-re

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!