Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource

Ashish Rai picture Ashish Rai · Nov 28, 2017 · Viewed 189.7k times · Source

I am trying to post data to an API from my localhost:4502 port. When i tried to post data to this API using POSTMAN the data got added in the backend by providing the Basic Authorization key. The same i am trying to implement here in the Ajax Jquery call, but getting an CORS error. First time in jquery i am trying to post the data, please help here, what i can add. I have got the API key to for the Basic Authorization as a Username and Password can be left blank.

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

  <script>
               $(document).ready(function(){
               $("#Save").click(function(){

                  var person = new Object();
                  person.Name = $('#Name').val();
                  person.EmailAddress = $('#EmailAddress').val();
                  person.CustomFields = [0];
                  person.CustomFields[0].Key = "[Country]";
                  person.CustomFields[0].Value = $('#Country').val();;

               $.ajax({
                 url: 'https://api.createsend.com/api/v3.1/subscribers/7c7a6087b0e450ad72b38be83098e271.json',
                 type: 'POST',
                 dataType: 'json',
                 data:person,
                 success: function(data,textStatus,xhr){

                     console.log(data);
                 },
                 error: function(xhr,textStatus,errorThrown){
                     console.log('Error Something');
                 },
                 beforeSend: function(xhr) {

                    xhr.setRequestHeader("Authorization", "Basic OTdlMjVmNWJiMTdjNzI2MzVjOGU3NjlhOTI3ZTA3M2Q5MWZmMTA3ZDM2YTZkOWE5Og=="); 
                 }
             });
         });
     });
  </script>

Answer

Hunter picture Hunter · Mar 10, 2018

I have added dataType: 'jsonp' and it works!

$.ajax({
   type: 'POST',
   crossDomain: true,
   dataType: 'jsonp',
   url: '',
   success: function(jsondata){

   }
})

JSONP is a method for sending JSON data without worrying about cross-domain issues. Read More