0

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.
Emac
  • 1,098
  • 3
  • 18
  • 37

1 Answers1

1

You are perfectly wright, CORS is preventing you to consume the API, unless explicitly allowed by the provider via 'Access-Control-Allow-Origin' header. There is no way to bypass this, it's enforced by the browser security policy. If available try JSONP. Also if this could work for you, I am not sure what the API does, you can use some sort of proxy script hosted on your domain, an API middleman to access remote API from an API hosted under your domain to pass CORS.