How to get a cross-origin resource sharing (CORS) post request working

后端 未结 11 2170
野趣味
野趣味 2020-11-21 22:35

I have a machine on my local lan (machineA) that has two web servers. The first is the in-built one in XBMC (on port 8080) and displays our library. The second server is a

相关标签:
11条回答
  • 2020-11-21 23:33

    REQUEST:

     $.ajax({
                url: "http://localhost:8079/students/add/",
                type: "POST",
                crossDomain: true,
                data: JSON.stringify(somejson),
                dataType: "json",
                success: function (response) {
                    var resp = JSON.parse(response)
                    alert(resp.status);
                },
                error: function (xhr, status) {
                    alert("error");
                }
            });
    

    RESPONSE:

    response = HttpResponse(json.dumps('{"status" : "success"}'))
    response.__setitem__("Content-type", "application/json")
    response.__setitem__("Access-Control-Allow-Origin", "*")
    
    return response
    
    0 讨论(0)
  • 2020-11-21 23:33

    Well I struggled with this issue for a couple of weeks.

    The easiest, most compliant and non hacky way to do this is to probably use a provider JavaScript API which does not make browser based calls and can handle Cross Origin requests.

    E.g. Facebook JavaScript API and Google JS API.

    In case your API provider is not current and does not support Cross Origin Resource Origin '*' header in its response and does not have a JS api (Yes I am talking about you Yahoo ),you are struck with one of three options-

    1. Using jsonp in your requests which adds a callback function to your URL where you can handle your response. Caveat this will change the request URL so your API server must be equipped to handle the ?callback= at the end of the URL.

    2. Send the request to your API server which is controller by you and is either in the same domain as the client or has Cross Origin Resource Sharing enabled from where you can proxy the request to the 3rd party API server.

    3. Probably most useful in cases where you are making OAuth requests and need to handle user interaction Haha! window.open('url',"newwindowname",'_blank', 'toolbar=0,location=0,menubar=0')

    0 讨论(0)
  • 2020-11-21 23:33

    This is a summary of what worked for me:

    Define a new function (wrapped $.ajax to simplify):

    jQuery.postCORS = function(url, data, func) {
      if(func == undefined) func = function(){};
      return $.ajax({
        type: 'POST', 
        url: url, 
        data: data, 
        dataType: 'json', 
        contentType: 'application/x-www-form-urlencoded', 
        xhrFields: { withCredentials: true }, 
        success: function(res) { func(res) }, 
        error: function() { 
                func({}) 
        }
      });
    }
    

    Usage:

    $.postCORS("https://example.com/service.json",{ x : 1 },function(obj){
          if(obj.ok) {
               ...
          }
    });
    

    Also works with .done,.fail,etc:

    $.postCORS("https://example.com/service.json",{ x : 1 }).done(function(obj){
          if(obj.ok) {
               ...
          }
    }).fail(function(){
        alert("Error!");
    });
    

    Server side (in this case where example.com is hosted), set these headers (added some sample code in PHP):

    header('Access-Control-Allow-Origin: https://not-example.com');
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 604800');
    header("Content-type: application/json");
    $array = array("ok" => $_POST["x"]);
    echo json_encode($array);
    

    This is the only way I know to truly POST cross-domain from JS.

    JSONP converts the POST into GET which may display sensitive information at server logs.

    0 讨论(0)
  • 2020-11-21 23:34

    I had the exact same issue where jquery ajax only gave me cors issues on post requests where get requests worked fine - I tired everything above with no results. I had the correct headers in my server etc. Changing over to use XMLHTTPRequest instead of jquery fixed my issue immediately. No matter which version of jquery I used it didn't fix it. Fetch also works without issues if you don't need backward browser compatibility.

            var xhr = new XMLHttpRequest()
            xhr.open('POST', 'https://mywebsite.com', true)
            xhr.withCredentials = true
            xhr.onreadystatechange = function() {
              if (xhr.readyState === 2) {// do something}
            }
            xhr.setRequestHeader('Content-Type', 'application/json')
            xhr.send(json)
    

    Hopefully this helps anyone else with the same issues.

    0 讨论(0)
  • 2020-11-21 23:35

    This is a little late to the party, but I have been struggling with this for a couple of days. It is possible and none of the answers I found here have worked. It's deceptively simple. Here's the .ajax call:

        <!DOCTYPE HTML>
        <html>
        <head>
        <body>
         <title>Javascript Test</title>
         <script src="http://code.jquery.com/jquery-latest.min.js"></script>
         <script type="text/javascript">
         $(document).domain = 'XXX.com';
         $(document).ready(function () {
         $.ajax({
            xhrFields: {cors: false},
            type: "GET",
            url: "http://XXXX.com/test.php?email='steve@XXX.com'",
            success: function (data) {
               alert(data);
            },
            error: function (x, y, z) {
               alert(x.responseText + " :EEE: " + x.status);
            }
        });
        });
        </script> 
        </body>
        </html>

    Here's the php on the server side:

        <html>
        <head>
         <title>PHP Test</title>
         </head>
        <body>
          <?php
          header('Origin: xxx.com');
          header('Access-Control-Allow-Origin:*');
          $servername = "sqlxxx";
          $username = "xxxx";
          $password = "sss";
          $conn = new mysqli($servername, $username, $password);
          if ($conn->connect_error) {
            die( "Connection failed: " . $conn->connect_error);
          }
          $sql = "SELECT email, status, userdata  FROM msi.usersLive";
          $result = $conn->query($sql);
          if ($result->num_rows > 0) {
          while($row = $result->fetch_assoc()) {
            echo $row["email"] . ":" . $row["status"] . ":" . $row["userdata"] .  "<br>";
          }
        } else {
          echo "{ }";
        }
        $conn->close();
        ?>
        </body>

    0 讨论(0)
提交回复
热议问题