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.
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;
};