I need to contact a server to consume a HTTP service.
Trying to reach the service with the browser, using https://example.com/service
I get the basic authentication dialog.
Changing the URL to https://username:[email protected]/service
easily bypasses that.
Trying to do the same using Ajax always results in 401 Unauthorized
though:
$.ajax({
url: 'https://username:[email protected]/service',
// rest repeats
type: "GET",
async: true,
success: function(text) { alert('success'); },
error: function (text) { alert('error') },
complete: function(text) { alert('complete'); }
});
$.ajax({
url: 'https://example.com/service',
username: username,
password: password,
// snip repeat
});
$.ajax({
url: 'https://example.com/service',
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic "
+ btoa(username + ":" + password));
},
// snip repeat
});
HTTP Request: GET vs. POSTGET is basically used for just getting (retrieving) some data from the server. Note: The GET method may return cached data. POST can also be used to get some data from the server. However, the POST method NEVER caches data, and is often used to send data along with the request.
We can do HTTP basic authentication URL with @ in password. We have to pass the credentials appended with the URL. The username and password must be added with the format − https://username:password@URL.
I struggled with a similar scenario myself.. What did the trick was using jsonp (ugh):
$.ajax({
url: "https://localhost:8443/v1/accounts",
type: 'GET',
dataType: 'jsonp',
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Basic bHVpZ2lAZ21haWwuY29tOmFiYzEyMzQ1');
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With