jQuery和跨域POST请求

Ces*_*sar 7 jquery http-post cross-domain-policy

我正在开发一个jQuery插件,它将成为某些REST API的连接器.实施是直截了当的,但同样的原产地政策肯定是痛苦的.我需要执行大多数POST请求.

我也尝试实现OPTIONS方法并返回(是python,但意思应该是清楚的)

def options(self):
  self.response.headers['Access-Control-Allow-Origin'] = self.request.host_url
  self.response.headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
  self.response.headers['Access-Control-Allow-Headers'] = 'x-requested-with'
  self.response.headers['Access-Control-Max-Age'] = '1728000'
Run Code Online (Sandbox Code Playgroud)

仍然不起作用......任何想法?

PS:我已经看到有类似主题的其他问题,但我需要POST方法的特定解决方案(使用iframe可以轻松实现GET)

Javascript示例:

$.ajax({
    url: options.protocol+'://'+options.host+':'+options.port+'/'+method,
    data: rawData,
    async:false,
    dataType: "json",
    type:"POST",
    success:function(data)
    {
        alert('asd');
        result.data = data;
        alert(data);
    },
    error:function(lol){
        alert('omggg !!!!'+lol);
    }

});
Run Code Online (Sandbox Code Playgroud)

编辑:添加了javascript代码示例

T.J*_*der 9

有时候这有点小提琴,有些想法:

  • CORS仅支持相当现代的浏览器,因此您需要确保使用其中一种.
  • IE只支持通过XDomainRequest对象的CORS ,而不是标准XMLHttpRequest对象,但是jQuery并没有特别满足(但是我不得不承认我有点惊讶并期望它会在不久之前),所以你必须添加特殊处理使这项工作在IE(然后只有IE8及以上).编辑:令人震惊的是,显然jQuery团队已经有了这个请求并拒绝了它:机票#8283没有任何意义.
  • 你确定这个Access-Control-Allow-Origin价值吗?它看起来像它仅允许从它的服务器访问.该标头用于指定服务器允许请求来自哪些来源.(并*允许,意思是"任何地方.")
  • 我似乎记得从我在Firefox上的实验中得知,在回应OPTIONS它没有要求的请求时我的允许方法很挑剔.
  • 仔细检查您是否允许请求发送的所有标头; 在你的例子中看起来你只允许一个header(x-requested-with),但我打赌在实际请求中会有其他人.

FWIW(我不是Python人),这是我的JSP代码,它可能有用 - 我认为即使你不做Java,对象名称也足够清晰可读(并且谁知道,也许你做):

String corsOrigin, corsMethod, corsHeaders;

// Find out what the request is asking for
corsOrigin = request.getHeader("Origin");
corsMethod = request.getHeader("Access-Control-Request-Method");
corsHeaders = request.getHeader("Access-Control-Request-Headers");
if (corsOrigin == null || corsOrigin.equals("null")) {
    // Requests from a `file://` path seem to come through without an
    // origin or with "null" (literally) as the origin.
    // In my case, for testing, I wanted to allow those and so I output
    // "*", but you may want to go another way.
    corsOrigin = "*";
}

// Add headers allowing specifically what was requested
response.addHeader("Access-Control-Allow-Origin", corsOrigin);
response.addHeader("Access-Control-Allow-Methods", corsMethod);
response.addHeader("Access-Control-Allow-Headers", corsHeaders);
if (request.getMethod().equals("OPTIONS"))
{
    // Done, no body in response to OPTIONS
    return;
}
// Processing the GET or POST here; output the body of the response
Run Code Online (Sandbox Code Playgroud)

请注意,我使用完全相同的逻辑GET,POST以及OPTIONS除了在选项的情况下,我不输出响应主体.