How to make dojo.request.xhr GET request with basic authentication

久未见 提交于 2019-12-07 08:02:26

问题


I look at the documentation for Dojo v.1.9 request/xhr and I cannot find example that includes basic authentication.

How and where do I include the User name and Password in the Dojo XHR options?

require(["dojo/request/xhr"], function(xhr){
  xhr("example.json", {
    // Include User and Password options here ?
    user: "userLogin"
    password: "userPassword"
    handleAs: "json"
  }).then(function(data){
    // Do something with the handled data
  }, function(err){
    // Handle the error condition
  }, function(evt){
    // Handle a progress event from the request if the
    // browser supports XHR2
  });
});

Thanks.


回答1:


Indeed, you should be able to pass the user and password with the user and password property in the options object.

In previous versions of Dojo this was documented, but it seems that now they aren't. However, I just tested it and it seems to add the username and password to the URL, like:

http://user:password@myUrl/example.json

Normally the browser should be capable of translating this URL so the request headers are set.


You could also set these headers manually, for example by using:

xhr("example.json", {
    headers: {
        "Authorization": "Basic " + base64.encode(toByteArray(user + ":" + pass))
    }
}).then(function(data) {
    // Do something 
});

However, this requires the dojox/encoding/base64 module and the following function:

var toByteArray = function(str) {
    var bytes = [];
    for (var i = 0; i < str.length; ++i) {
        bytes.push(str.charCodeAt(i));
    }
    return bytes;
};


来源:https://stackoverflow.com/questions/22054559/how-to-make-dojo-request-xhr-get-request-with-basic-authentication

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