I've read many threads about trying to login to a site's API using Basic authorization using Javascript, and I feel like I've tried all advice I've seen, but I can't get it to work. I have a feeling it may be a two-fold problem as I'm getting a 401 error and also a No Access-Control-Allow-Origin error.
Can someone please explain to me what I'm doing wrong? I have tried including the authorization a few different ways, but the results always end up being the same. I can connect to the same API using Basic authorization via Python and Postman, so not sure why Javascript won't work for me. Go easy on me, I'm new to Javascript!
Here is my script:
function logIn() {
var userName = document.getElementById("username").value;
var pWord = document.getElementById("password").value;
console.log("Your username is: " + userName);
$.ajax
({
type: "GET",
url: "https://example.com",
dataType: 'json',
async: false,
headers: {
"Authorization": "Basic " + btoa(userName + ":" + pWord)
},
success: function (){
alert('Thanks for logging in!');
}
});
}
And I am getting these errors:
GET https://example.com 401 (Please log in.)
Failed to load https://example.com 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 401.