问题
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