Cross domain POST query using Cross-Origin Resource Sharing getting no data back

后端 未结 4 1296
独厮守ぢ
独厮守ぢ 2020-12-08 12:09

I\'m sending data cross domain via a POST request but the response isn\'t working, specifically, jQuery\'s success handler never gets called.

Stuff being used: Djang

相关标签:
4条回答
  • 2020-12-08 12:40

    I don't think this is possible for security reasons. The only cross domain ajax calls which browsers allow, can be done using JSONP and these are exclusively GET requests.

    This will work:

    $.ajax({
        url: "http://somesite.com/someplace",
        type: "GET",
        cache: false,
        dataType: "JSONP",
        data: { ... },
        success: function( msg ) {
            alert(msg);
        },
    });
    

    This won't:

    $.ajax({
        url: "http://somesite.com/someplace",
        type: "POST",
        cache: false,
        dataType: "JSONP",
        data: { ... },
        success: function( msg ) {
            alert(msg);
        },
    });
    
    0 讨论(0)
  • 2020-12-08 12:52

    For any future searchers who may come across this posting, the following resource is the W3C 2008 working-draft which discusses CORS in-depth.

    http://www.w3.org/TR/2008/WD-access-control-20080912/

    As of the time of this posting, it should be noted that Chromium specifically, and probably all of WebKit has a bug which prevents the Access-Control-Max-Age header's value from being honored. Details on this can be found on the discussion page for Chromium Issue 131368. In summary - as of now, WebKit-based browsers will override whatever the server returns as a value here with 600 (10 minutes).

    0 讨论(0)
  • 2020-12-08 13:03

    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-12-08 13:05

    Ok, so I believe the correct way to do things is this:

    if request.method == "POST":
        response = HttpResponse(simplejson.dumps(data),mimetype='application/json')
        response['Access-Control-Allow-Origin'] = "*"
        return response
    elif request.method == "OPTIONS":
        response = HttpResponse("")
        response['Access-Control-Allow-Origin'] = "*"
        response['Access-Control-Allow-Methods'] = "POST, OPTIONS"
        response['Access-Control-Allow-Headers'] = "X-Requested-With"
        response['Access-Control-Max-Age'] = "1800"
    else:
        return HttpResponseBadRequest()
    

    This is based on the documentation I dug up from Mozilla on preflighted requests.

    So, what I believe will happen is this:

    1. If there's nothing in the preflight cache, OPTIONS is sent with X-Requested-With set to XMLHttpRequest I believe this is necessary to allow Javascript access to anything, along with an Origin header.
    2. The server can examine that information. That is the security of CORS. In my case, I'm responding with "any origin will do" and "you're allowed to send the X-Requested-With thing". I'm saying that OPTIONS and POST are allowed and that this response should be cached for 30 mins.
    3. The client then goes ahead and makes the POST, which was working before.
    4. I modified the response originally to include Allow-Methods and Allow-Headers but according to the exchange in the above linked documentation this isn't needed. This makes sense, the access check has already been done.
    5. I believe then that what happens is the resource sharing check described here. Basically, once said request has been made, the browser again checks the Allow-Origin field for validity, this being on the request such as POST. If this passes, the client can have access to the data, if not, the request has already completed but the browser denies the actual client side application (Javascript) access to that data.

    I believe that is a correct summary of what is going on and in any case it appears to work. If I'm not right, please shout.

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