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

后端 未结 11 2220
野趣味
野趣味 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

    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.

提交回复
热议问题