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

6

41

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>
Inflexion answered 28/11, 2017 at 3:1 Comment(5)
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.Shawanda
You're looking for JSONP for Cross-Domain AJAX requests.Mayflower
@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?Inflexion
@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. tutorialspoint.com/nodejs <- A slight start to understanding Node is that. Happy coding and GLShawanda
@Shawanda What?Drislane
W
65

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

Wapiti answered 10/3, 2018 at 21:32 Comment(6)
If someone wants the explanation for this: https://mcmap.net/q/18436/-loading-cross-domain-endpoint-with-ajaxFebruary
and this solution does not work it the remote does not reply with jsonpGanger
give this guy a medal.Bainite
God bless you. Have a nice next 36 hours.Drislane
BTW, the type: 'POST' won't work, because the jsonp dataType creates a <script> element to fetch data, which has to be a GET requestPeipeiffer
how about i don't want to send json but i also don't want to worry abput cors?Tseng
S
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....

Sundog answered 19/10, 2018 at 15:16 Comment(0)
P
6

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){

   }
})
Priorate answered 28/11, 2017 at 6:48 Comment(4)
Thank you, i will try to add the Allow-Origin thing at the API level and see. I hope it works :)Inflexion
tell me if it works, if it didnt work, add a screenshot of the error, thank you!Priorate
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 successMussulman
I cant understand why 'Access-Control-Allow-Origin' added in this ajax header? it must be added on our server side right?Licensee
B
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."

Buchanan answered 13/3, 2019 at 15:59 Comment(0)
L
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 :)

Lauralauraceous answered 4/8, 2022 at 9:41 Comment(0)
S
-3

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

Santo answered 6/1, 2020 at 14:57 Comment(1)
This post isn't an actual attempt at answering the question. Please note StackOverflow doesn't work like a discussion forum, it is a Q&A site where every post is either a question or an answer to a question. Posts can also have comments - 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 questionEmrick

© 2022 - 2024 — McMap. All rights reserved.