How to assign basic authentication header to XMLHTTPREQUEST?

前端 未结 4 762
闹比i
闹比i 2020-12-14 02:05

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 cli

相关标签:
4条回答
  • 2020-12-14 02:10

    Solution:

    req.setRequestHeader('Authorization', 'Basic [base64 encoded password here]' );
    
    0 讨论(0)
  • 2020-12-14 02:15

    If using this for an API request, adding the Authorization header will first make XMLHttpRequest send an OPTIONS request, which may be denied by some APIs.

    To get around this you can also do:

    var invocation = new XMLHttpRequest();
    invocation.open("GET", url, true, username, password);
    invocation.withCredentials = true;
    

    Which will add the Authorization header and also avoid the preflight request.

    0 讨论(0)
  • 2020-12-14 02:16

    If you want to set the authorization header

    req.setRequestHeader('Authorization','Basic ' + Base64StringOfUserColonPassword);
    
    0 讨论(0)
  • 2020-12-14 02:16

    This post is old, but answering for anybody else who comes across it.

    There is nothing wrong with your authorization header. The problem you are facing is CORS related.

    You don't set the Origin header yourself. The browser does that for you. If your origin is null then I suspect this is because you are running your code from file:/// instead of http://.

    0 讨论(0)
提交回复
热议问题