我在本地局域网(machineA)上有一台具有两个Web服务器的计算机。第一个是XBMC中的内置端口(在端口8080上),并显示我们的库。第二台服务器是我用来根据需要触发文件转换的CherryPy python脚本(端口8081)。由XBMC服务器提供的页面上的AJAX POST请求触发文件转换。
jQuery Ajax请求
$.post('http://machineA:8081', {file_url: 'asfd'}, function(d){console.log(d)})
请求标头-选项
Host: machineA:8081 User-Agent: ... Firefox/4.01 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 115 Connection: keep-alive Origin: http://machineA:8080 Access-Control-Request-Method: POST Access-Control-Request-Headers: x-requested-with
响应标题-选项(状态= 200 OK)
Content-Length: 0 Access-Control-Allow-Headers: * Access-Control-Max-Age: 1728000 Server: CherryPy/3.2.0 Date: Thu, 21 Apr 2011 22:40:29 GMT Access-Control-Allow-Origin: * Access-Control-Allow-Methods: POST, GET, OPTIONS Content-Type: text/html;charset=ISO-8859-1
为了进行故障排除,我还从http://jquery.com发出了相同的$ .post命令。这是我在jquery.com遇到麻烦的地方,发布请求有效,OPTIONS请求由POST发送。该事务的标题在下面;
Host: machineA:8081 User-Agent: ... Firefox/4.01 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 115 Connection: keep-alive Origin: http://jquery.com Access-Control-Request-Method: POST
Content-Length: 0 Access-Control-Allow-Headers: * Access-Control-Max-Age: 1728000 Server: CherryPy/3.2.0 Date: Thu, 21 Apr 2011 22:37:59 GMT Access-Control-Allow-Origin: * Access-Control-Allow-Methods: POST, GET, OPTIONS Content-Type: text/html;charset=ISO-8859-1
请求标头-POST
Host: machineA:8081 User-Agent: ... Firefox/4.01 Accept: */* Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 115 Connection: keep-alive Content-Type: application/x-www-form-urlencoded; charset=UTF-8 Referer: http://jquery.com/ Content-Length: 12 Origin: http://jquery.com Pragma: no-cache Cache-Control: no-cache
响应标头-POST(状态= 200 OK)
Content-Length: 32 Access-Control-Allow-Headers: * Access-Control-Max-Age: 1728000 Server: CherryPy/3.2.0 Date: Thu, 21 Apr 2011 22:37:59 GMT Access-Control-Allow-Origin: * Access-Control-Allow-Methods: POST, GET, OPTIONS Content-Type: application/json
我无法弄清楚为什么相同的请求会在一个站点上起作用,而在另一个站点上却不起作用。我希望有人能够指出我所缺少的。谢谢你的帮助!
我最终偶然发现了此链接“ CORS POST请求可通过普通javascript运行,但为什么不使用jQuery? ”指出jQuery 1.5.1添加了
Access-Control-Request-Headers: x-requested-with
所有CORS请求的标头。jQuery 1.5.2不会这样做。另外,根据相同的问题,设置服务器响应标头为
Access-Control-Allow-Headers: *
不允许响应继续。您需要确保响应标头专门包含必需的标头。即:
Access-Control-Allow-Headers: x-requested-with