39

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>
Jongware
  • 22,200
  • 8
  • 54
  • 100
Ashish Rai
  • 391
  • 1
  • 3
  • 4
  • 1
    What you are trying to do is access an api through AJAX. This isn't possible (theoretically, it is, but I'm not going to get into that). You should be using a server language (PHP, Node.js, etc) to make an HTTP request to the api. From there, you can take the data and use it as you'd like. – UghThatGUyAgain Nov 28 '17 at 03:02
  • 2
    You're looking for [**JSONP**](https://en.wikipedia.org/wiki/JSONP) for Cross-Domain AJAX requests. – Obsidian Age Nov 28 '17 at 03:05
  • @UghThatGuyAgain Thank you for your reply. so you meant i need to write the same call in either of this like php or node.js? – Ashish Rai Nov 28 '17 at 03:17
  • @AshishRai Yes; However, it's more than that. The backend language needs to be able to communicate with the frontend. It's more than just rewriting the same call, because HTTP is a whole different field than AJAX. Once you learn how to make the HTTP call with the backend, you then need to learn how to communicate it to the frontend (With Node, it's not that hard, imo). So, to finish this off: Node.js or PHP will allow you to make the call, and then you can communicate it to the frontend. https://www.tutorialspoint.com/nodejs/ <- A slight start to understanding Node is that. Happy coding and GL – UghThatGUyAgain Nov 28 '17 at 03:23
  • @UghThatGUyAgain What? – Čamo Aug 31 '21 at 16:44

6 Answers6

61

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

Nanhe Kumar
  • 15,498
  • 5
  • 79
  • 71
Hunter
  • 3,080
  • 20
  • 23
7

Its a CORS issue, your api cannot be accessed directly from remote or different origin, In order to allow other ip address or other origins from accessing you api, you should add the 'Access-Control-Allow-Origin' on the api's header, you can set its value to '*' if you want it to be accessible to all, or you can set specific domain or ips like 'http://siteA.com' or 'http://192. ip address ';

Include this on your api's header, it may vary depending on how you are displaying json data,

if your using ajax, to retrieve and display data your header would look like this,

$.ajax({
   url: '',
   headers: {  'Access-Control-Allow-Origin': 'http://The web site allowed to access' },
   data: data,
   type: 'dataType',
   /* etc */
   success: function(jsondata){

   }
})
Vombat
  • 1,156
  • 1
  • 15
  • 27
apelidoko
  • 782
  • 1
  • 7
  • 23
  • Thank you, i will try to add the Allow-Origin thing at the API level and see. I hope it works :) – Ashish Rai Nov 28 '17 at 07:45
  • tell me if it works, if it didnt work, add a screenshot of the error, thank you! – apelidoko Nov 28 '17 at 07:46
  • it doesn't work for me .... I am trying to call elasticsearch servers from a Tomcat JSP page hosted on my laptop and getting the error. I have tried also headers: `{ 'Access-Control-Allow-Origin': '*' },` but with no success – Reddy SK Feb 25 '19 at 15:17
  • 22
    I cant understand why 'Access-Control-Allow-Origin' added in this ajax header? it must be added on our server side right? – Ameerudheen.K Jun 08 '20 at 11:13
7

If you are using NodeJs for your server side, just add these to your route and you will be Ok

     res.header("Access-Control-Allow-Origin", "*");
     res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

Your route will then look somehow like this

    router.post('/odin', function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");


    return res.json({Name: req.body.name, Phone: req.body.phone});
});

Client side for Ajax call

 var sendingData = {
   name: "Odinfono Emmanuel",
   phone: "1234567890"
}

<script>
  $(document).ready(function(){

    $.ajax({
        url: 'http://127.0.0.1:3000/odin',            
        method: 'POST',
        type: 'json',
        data: sendingData,
        success: function (response) {
            console.log(response);
        },
        error: function (error) {
            console.log(error);
        }
        });
    });
</script>

You should have something like this in your browser console as response

{ name: "Odinfono Emmanuel", phone: "1234567890"}

Enjoy coding....

Enamul Haque
  • 144
  • 9
Odin
  • 921
  • 8
  • 12
2

Be aware to use constant HTTPS or HTTP for all requests. I had the same error msg: "No 'Access-Control-Allow-Origin' header is present on the requested resource."

0

I had this problem and resolved by adding a content type header. I don't know why that worked, but I had noticed other post requests that worked had content type set. The one that was failing didn't have one because it had no content. I hope this helps someone :)

UglyBlueCat
  • 439
  • 1
  • 7
  • 22
-3

If the requested resource of the server is using Flask. Install Flask-CORS.

Johnson
  • 13
  • 1
  • 1
    This post isn't an actual attempt at answering the question. Please note [StackOverflow doesn't work like a discussion forum](http://stackoverflow.com/tour), it is a Q&A site where every post is either a question or an answer to a question. Posts can also have [comments](http://stackoverflow.com/help/privileges/comment) - small sentences like this one - that can be used to critique or request clarification from an author. This should be either a comment or a [new question](http://stackoverflow.com/questions/ask) – ρяσѕρєя K Jan 06 '20 at 15:17