使用跨源资源共享的跨域 POST 查询没有返回数据

发布于 2024-10-21 06:15:37 字数 1796 浏览 4 评论 0原文

我通过 POST 请求跨域发送数据,但响应不起作用,具体来说,jQuery 的成功处理程序永远不会被调用。

使用的东西:Django、Apache、jQuery。

因此,我设置了一个与此类似的请求:

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

正如您所知, CORS 允许我要适当地回应 OPTIONS 查询,说“是的,你可以 POST 给我”。我正在做的事。 Firebug 确认我收到了 200 状态代码,并且返回类型实际上是 application/json。但是,Firebug 还确认上面的成功处理程序没有被调用。

作为参考,我对 OPTIONS 的回应是:

elif request.method == "OPTIONS":
    response = HttpResponse("")
    response['Access-Control-Allow-Origin'] = "*"
    response['Access-Control-Allow-Methods'] = "POST, GET, OPTIONS"
    response['Access-Control-Allow-Headers'] = "X-Requested-With"
    return response

相反,如果我设置了一个complete: function()... 处理程序,它就可以工作。

所以,问题是:发生了什么(或没有发生)以及为什么?我得到的数据很好,我只想能够返回响应。


更新这解决了我在某些浏览器上的问题,但由于我对此行为没有完整明确的解释,因此我将其保持打开状态

好的,所以我阅读了手册以及我对它的理解,所应用的算法大致是this:

  1. 用户代理可以实现预检调用。这是OPTIONS 请求。这个想法是,他们发出这个请求,为他们提供有关所请求资源的答案,然后他们应该缓存该资源。 我没有传回 max-age 字段,因此我怀疑虽然返回成功并且允许 X 请求,但用户代理的缓存中没有任何内容允许我进行此操作,因此应用默认规则(隔离请求)。
  2. 当您发出实际请求时,我相信用户代理应该检查飞行前缓存的权限。如果没有我的 max-age 字段,我相信它找不到这些权限。但是,在 POST 上使用相同的标头进行响应似乎允许 Firefox 和 Google Chrome 查看响应。歌剧不能。 IE 目前尚未经过测试。

我目前不明白,并且从手册中也不清楚(至少对我来说)CORS 请求是否也应该使用请求中的这些标头以及 OPTIONS 进行应答。我将尝试使用 Max-Age 标头,看看允许或不允许什么。然而,我对这个问题仍然缺乏一些明确的权威理解,所以如果这里有人知道的话,我洗耳恭听。

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: Django, Apache, jQuery.

So, I set up a request rather similar to this:

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

As you well know, CORS allows me to respond to an OPTIONS query appropriately to say "Yes, you can POST to me". Which I'm doing. Firebug confirms I'm getting my 200 status code and that the return type is in fact application/json. However, Firebug also confirms that the success handler in the above is not being called.

For reference, my response to OPTIONS is:

elif request.method == "OPTIONS":
    response = HttpResponse("")
    response['Access-Control-Allow-Origin'] = "*"
    response['Access-Control-Allow-Methods'] = "POST, GET, OPTIONS"
    response['Access-Control-Allow-Headers'] = "X-Requested-With"
    return response

In contrast, if I set up a complete: function()... handler it works.

So, question is: what's happening (or not) and why? I am getting data fine, I'd just like to be able to return the response.


Update: This fixes my issue on some browsers but since I don't have a complete definite explanation to this behaviour I'm leaving it open.

Ok, so I read the manual and what I understand of it, the algorithm applied is roughly this:

  1. User agents may implement a preflight call. This is the OPTIONS request. The idea is that they make this request which gives them an answer with respect to the requested resource, which they are then supposed to cache. I'm not passing back a max-age field, so I suspect whilst success is being returned and the X-request allowed, there is nothing in the user agent's cache which permitted me to make it, so the default rules (isolate the request) are applied.
  2. When you make the actual request, I believe the user agent is supposed to inspect the pre-flight cache for permissions. Without my max-age field, I believe it isn't finding these permissions. However, responding with the same headers on POST appears to allow Firefox and Google Chrome to view the response. Opera can not. IE remains untested at the moment.

I do not currently understand and it is not clear from the manual (to me at least) whether a CORS request should also answer with these headers in the request as well as the OPTIONS. I shall experiment with the Max-Age header and see what that allows or does not allow. However, I'm still short of some definite authoritative understanding on the issue so if there is someone on here who knows, I'm all ears.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

山人契 2024-10-28 06:15:37

好的,所以我相信正确的做事方法是这样的:

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()

这是基于我从 Mozilla 挖出的文档 关于预检请求。

所以,我相信会发生的是这样的:

  1. 如果预检缓存中没有任何内容,则发送 OPTIONS 并将 X-Requested-With 设置为 XMLHttpRequest > 我相信这是允许 Javascript 访问任何内容以及 Origin 标头所必需的。
  2. 服务器可以检查该信息。 这就是 CORS 的安全性。就我而言,我的回应是“任何来源都可以”和“您可以发送X-Requested-With”。我是说允许 OPTIONSPOST,并且该响应应该缓存 30 分钟。
  3. 然后客户端继续进行 POST,这在之前是有效的。
  4. 我最初修改了响应以包含 Allow-MethodsAllow-Headers 但根据上面链接文档中的交换,这是不需要的。这是有道理的,访问检查已经完成。
  5. 我相信接下来会发生此处描述的资源共享检查。基本上,一旦发出所述请求,浏览器就会再次检查 Allow-Origin 字段的有效性,这是针对 POST 等请求的。如果通过,则客户端可以访问数据,如果没有,则请求已完成,但浏览器拒绝实际的客户端应用程序 (Javascript) 访问该数据。

我相信这是对正在发生的事情的正确总结,并且无论如何它似乎都是有效的。如果我说得不对,请大声喊叫。

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.

对于任何可能遇到此帖子的未来搜索者,以下资源是 W3C 2008 工作草案,其中深入讨论了 CORS。

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

截至本文发布时,应该指出的是,特别是 Chromium,甚至可能所有 WebKit 都有一个错误,该错误会阻止 Access-Control-Max-Age 标题的价值得到尊重。有关详细信息,请参阅 Chromium 问题 131368。总之 - 截至目前,基于 WebKit 的浏览器将使用 600(10 分钟)覆盖服务器返回的任何值。

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).

无戏配角 2024-10-28 06:15:37

请求:

 $.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 = HttpResponse(json.dumps('{"status" : "success"}'))
response.__setitem__("Content-type", "application/json")
response.__setitem__("Access-Control-Allow-Origin", "*")

return response

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
踏月而来 2024-10-28 06:15:37

出于安全原因,我认为这是不可能的。浏览器允许的唯一跨域 ajax 调用可以使用 JSONP 来完成,并且这些都是专门的 GET 请求。

这会起作用:

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

这不会:

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

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);
    },
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文