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

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

    For some reason, a question about GET requests was merged with this one, so I'll respond to it here.

    This simple function will asynchronously get an HTTP status reply from a CORS-enabled page. If you run it, you'll see that only a page with the proper headers returns a 200 status if accessed via XMLHttpRequest -- whether GET or POST is used. Nothing can be done on the client side to get around this except possibly using JSONP if you just need a json object.

    The following can be easily modified to get the data held in the xmlHttpRequestObject object:

    function checkCorsSource(source) {
      var xmlHttpRequestObject;
      if (window.XMLHttpRequest) {
        xmlHttpRequestObject = new XMLHttpRequest();
        if (xmlHttpRequestObject != null) {
          var sUrl = "";
          if (source == "google") {
            var sUrl = "https://www.google.com";
          } else {
            var sUrl = "https://httpbin.org/get";
          }
          document.getElementById("txt1").innerHTML = "Request Sent...";
          xmlHttpRequestObject.open("GET", sUrl, true);
          xmlHttpRequestObject.onreadystatechange = function() {
            if (xmlHttpRequestObject.readyState == 4 && xmlHttpRequestObject.status == 200) {
              document.getElementById("txt1").innerHTML = "200 Response received!";
            } else {
              document.getElementById("txt1").innerHTML = "200 Response failed!";
            }
          }
          xmlHttpRequestObject.send();
        } else {
          window.alert("Error creating XmlHttpRequest object. Client is not CORS enabled");
        }
      }
    }
    
    
      Check if page is cors
    
    
      

    A CORS-enabled source has one of the following HTTP headers:

    • Access-Control-Allow-Headers: *
    • Access-Control-Allow-Headers: x-requested-with

    Click a button to see if the page allows CORS

提交回复
热议问题