Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign basic authentication header to XMLHTTPREQUEST?

I've read many answers of preflight and CORS so please do not post links referencing what I should read. Many of the answers are from a server-perspective, but I am the client in this case. Do I set the origin header? My assumption is that this is a simple request, am I right?

 req.open("POST", url, true);  req.setRequestHeader( 'Content-Type',   'application/blahblah' );  req.setRequestHeader( 'Accept', 'application/blahblah' );  req.setRequestHeader("Authorization", "Basic " + btoa(user + ":" + pass));   req.send(); 

Yet its still not working, my error:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 500.

like image 982
carrots Avatar asked Nov 03 '15 17:11

carrots


2 Answers

If you want to set the authorization header

req.setRequestHeader('Authorization','Basic ' + Base64StringOfUserColonPassword); 
like image 193
epascarello Avatar answered Oct 07 '22 06:10

epascarello


Solution:

var req = new XMLHttpRequest();     req.setRequestHeader('Authorization', 'Basic [base64 encoded password here]' ); 
like image 41
carrots Avatar answered Oct 07 '22 07:10

carrots