-1

// find elements
url = 'https://btacertified.com/api/v1/courses';
apitoken = 'RjBMcmlabzZIa3I0bExSM0ZadnN5MFpRNkg5Y3R6UmcyS25uaTFrZVRUcUQ3RUNBVkpHR09LWVNJbklG5c9a7a09c78b6';
var button = $("button")

$(document).ready(function() {
  // handle click and add class
  button.on("click", function() {

    $.ajax({
      url: url,
      type: "POST",
      crossDomain: true,
      data: JSON.stringify({
        "a": 1
      }),
      dataType: "jsonp",
      beforeSend: function(xhr) {
        xhr.withCredentials = true;
      },
      headers: {
        'Access-Control-Allow-Origin': 'https://jsfiddle.net',
        'Authorization': apitoken
      },
      success: function(response) {
        var resp = JSON.parse(response)
        alert(resp.status);
      },
      error: function(xhr, status) {
        alert("error");
      }
    });
  })
});
<!doctype html>
<html lang="en">

<head>
  <title></title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>
  <div id="banner-message">
    <button>Click Me</button>
  </div>
</body>

</html>

I am doing a post API with apitoken authorization in the header to retrieve a json.

I am getting a CORS error, which is "blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header".

P.S: I have checked similar CORS post nothing works for me, I have no control over the 3rd party API server, so I can not add any headers there. Using JSONP i get 405 error

But I can see results via apitest.com in the following link. https://apitester.com/shared/checks/27522c9ca1dc4e7f89fe488f3864909f

Ramji
  • 2,536
  • 7
  • 34
  • 54
  • 1
    If API is not CORS enabled or serves JSONP you need to use a proxy either on your server or third party service. Not uncommon so as to protect your credentials from being exposed in front end – charlietfl Apr 01 '19 at 05:47
  • Note that access control headers are useless in request headers...they must be set in response headers by endpoint – charlietfl Apr 01 '19 at 05:49

1 Answers1

-1

Charlietfl is correct but also, if you know the api can handle CORS requests, you may want to get rid of the access-control-allow-origin from your request (I believe this is a response header) and are you sure you want to set the data type to JSONP? Maybe get rid of this line and let the server decide (most API’s don’t require JSONP nowadays).