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

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

    If for some reasons while trying to add headers or set control policy you're still getting nowhere you may consider using apache ProxyPass…

    For example in one <VirtualHost> that uses SSL add the two following directives:

    SSLProxyEngine On
    ProxyPass /oauth https://remote.tld/oauth
    

    Make sure the following apache modules are loaded (load them using a2enmod):

    • proxy
    • proxy_connect
    • proxy_http

    Obviously you'll have to change your AJAX requests url in order to use the apache proxy…

    0 讨论(0)
  • 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");
        }
      }
    }
    <html>
    <head>
      <title>Check if page is cors</title>
    </head>
    <body>
      <p>A CORS-enabled source has one of the following HTTP headers:</p>
      <ul>
        <li>Access-Control-Allow-Headers: *</li>
        <li>Access-Control-Allow-Headers: x-requested-with</li>
      </ul>
      <p>Click a button to see if the page allows CORS</p>
      <form name="form1" action="" method="get">
        <input type="button" name="btn1" value="Check Google Page" onClick="checkCorsSource('google')">
        <input type="button" name="btn1" value="Check Cors Page" onClick="checkCorsSource('cors')">
      </form>
      <p id="txt1" />
    </body>
    </html>

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

    Took me some time to find the solution.

    In case your server response correctly and the request is the problem, you should add withCredentials: true to the xhrFields in the request:

    $.ajax({
        url: url,
        type: method,
        // This is the important part
        xhrFields: {
            withCredentials: true
        },
        // This is the important part
        data: data,
        success: function (response) {
            // handle the response
        },
        error: function (xhr, status) {
            // handle errors
        }
    });
    

    Note: jQuery >= 1.5.1 is required

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

    Using this in combination with Laravel solved my problem. Just add this header to your jquery request Access-Control-Request-Headers: x-requested-with and make sure that your server side response has this header set Access-Control-Allow-Headers: *.

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

    I solved my own problem when using google distance matrix API by setting my request header with Jquery ajax. take a look below.

    var settings = {
              'cache': false,
              'dataType': "jsonp",
              "async": true,
              "crossDomain": true,
              "url": "https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=place_id:"+me.originPlaceId+"&destinations=place_id:"+me.destinationPlaceId+"&region=ng&units=metric&key=mykey",
              "method": "GET",
              "headers": {
                  "accept": "application/json",
                  "Access-Control-Allow-Origin":"*"
              }
          }
    
          $.ajax(settings).done(function (response) {
              console.log(response);
    
          });
    

    Note what i added at the settings
    **

    "headers": {
              "accept": "application/json",
              "Access-Control-Allow-Origin":"*"
          }
    

    **
    I hope this helps.

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

    I finally stumbled upon this link "A CORS POST request works from plain javascript, but why not with jQuery?" that notes that jQuery 1.5.1 adds the

     Access-Control-Request-Headers: x-requested-with
    

    header to all CORS requests. jQuery 1.5.2 does not do this. Also, according to the same question, setting a server response header of

    Access-Control-Allow-Headers: *
    

    does not allow the response to continue. You need to ensure the response header specifically includes the required headers. ie:

    Access-Control-Allow-Headers: x-requested-with 
    
    0 讨论(0)
提交回复
热议问题