Search code examples
javascriptrestful-authenticationxmlhttprequest

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.


Solution

  • Solution:

    var req = new XMLHttpRequest();
        req.setRequestHeader('Authorization', 'Basic [base64 encoded password here]' );