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

2022-01-15 00:00:00 cors jquery javascript ajax cross-domain

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

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

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

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);
    },
});

众所周知,CORS 允许我回复 OPTIONS 适当地查询说是的,你可以发帖给我".我正在做的.Firebug 确认我收到了我的 200 状态代码,并且返回类型实际上是 application/json.但是,Firebug 也确认上面的成功处理程序没有被调用.

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.

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

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

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

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.

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

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

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

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

我目前不明白,从手册中也不清楚(至少对我而言)CORS 请求是否也应该在请求中使用这些标头以及 OPTIONS 来回答.我将试验 Max-Age 标头并查看允许或不允许的内容.但是,我对这个问题仍然缺乏一定的权威理解,所以如果这里有人知道,我会全力以赴.

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.

推荐答案

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

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

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

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

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

So, what I believe will happen is this:

  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) 访问该数据.
  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.

相关文章