注意:以下代码请在Firefox 3.5、Chrome 3.0、Safari 4之后的版本中进行测试。IE8的实现方法与其他浏览不同。
2,预检请求
预检请求首先需要向另外一个域名的资源发送一个 HTTP OPTIONS 请求头,其目的就是为了判断实际发送的请求是否是安全的。下面的2种情况需要进行预检:
a,不是上面的简单请求,比如使用Content-Type 为 application/xml 或 text/xml 的 POST 请求
b,在请求中设置自定义头,比如 X-JSON、X-MENGXIANHUI 等
注意:在 iis 里进行测试,必须在“应用程序扩展”里面配置 .aspx 扩展的动作允许 OPTIONS。
下面我们举一个预检的请求:
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title>孟宪会之AJAX跨域请求测试</title>
- </head>
- <body>
- <input type='button' value='开始测试' onclick='crossDomainRequest()' />
- <div id="content"></div>
- <mce:script type="text/javascript"><!--
- var xhr = new XMLHttpRequest();
- var url = 'http://dotnet.aspx.cc/PreflightedRequests.aspx';
- function crossDomainRequest() {
- document.getElementById("content").innerHTML = "开始进行请求……";
- if (xhr) {
- var xml = "<root>测试</root>";
- xhr.open('POST', url, true);
- xhr.setRequestHeader("POWERED-BY-MENGXIANHUI", "Approve");
- xhr.setRequestHeader("Content-Type", "application/xml");
- xhr.onreadystatechange = handler;
- xhr.send(xml);
- } else {
- document.getElementById("content").innerHTML = "不能创建 XMLHttpRequest。";
- }
- }
- function handler(evtXHR) {
- if (xhr.readyState == 4) {
- if (xhr.status == 200) {
- var response = xhr.responseText;
- document.getElementById("content").innerHTML = "结果:" + response;
- } else {
- document.getElementById("content").innerHTML = "不能进行跨越访问。";
- }
- }
- else {
- document.getElementById("content").innerHTML += "<br/>执行状态 readyState:" + xhr.readyState;
- }
- }
- // --></mce:script>
- </body>
- </html>
上面的例子我们发送 xml 格式的数据,并且,发送一个非标准的HTTP头 POWERED-BY-MENGXIANHUI 来说明服务器端该如何设置响应头的。
在服务器端,PreflightedRequests.aspx 的内容如下:
- <%@ Page Language="C#" %>
- <mce:script runat="server"><!--
- protected void Page_Load(object sender, EventArgs e)
- {
- if (Request.HttpMethod.Equals("GET"))
- {
- Response.Write("这个页面是用来测试跨域 POST 请求的,直接浏览意义不大。");
- }
- else if (Request.HttpMethod.Equals("OPTIONS"))
- {
- //通知客户端允许预检请求。并设置缓存时间
- Response.ClearContent();
- Response.AddHeader("Access-Control-Allow-Origin", "http://www.meng_xian_hui.com:801");
- Response.AddHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
- Response.AddHeader("Access-Control-Allow-Headers", "POWERED-BY-MENGXIANHUI");
- Response.AddHeader("Access-Control-Max-Age", "30");
- //此过程无需返回数据
- Response.End();
- }
- else if (Request.HttpMethod.Equals("POST"))
- {
- if (Request.Headers["Origin"].Equals("http://www.meng_xian_hui.com:801"))
- {
- System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
- doc.Load(Request.InputStream);
- Response.AddHeader("Access-Control-Allow-Origin", "http://www.meng_xian_hui.com:801");
- Response.Write("您提交的数据是:<br/><br/>" + Server.HtmlEncode(doc.OuterXml));
- }
- else
- {
- Response.Write("不允许你的网站请求。");
- }
- }
- }
- // --></mce:script>
点击“开始测试”按钮,将会执行下面的一系列请求。
- OPTIONS /PreflightedRequests.aspx HTTP/1.1
- Host: dotnet.aspx.cc
- User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)
- Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
- Accept-Language: zh-cn,zh;q=0.5
- Accept-Encoding: gzip,deflate
- Accept-Charset: GB2312,utf-8;q=0.7,*;q=0.7
- Keep-Alive: 300
- Connection: keep-alive
- Origin: http://www.meng_xian_hui.com:801
- Access-Control-Request-Method: POST
- Access-Control-Request-Headers: powered-by-mengxianhui
- HTTP/1.x 200 OK
- Date: Sun, 10 Jan 2010 14:00:34 GMT
- Server: Microsoft-IIS/6.0
- X-Powered-By: ASP.NET
- X-AspNet-Version: 2.0.50727
- Access-Control-Allow-Origin: http://www.meng_xian_hui.com:801
- Access-Control-Allow-Methods: POST, GET, OPTIONS
- Access-Control-Allow-Headers: POWERED-BY-MENGXIANHUI
- Access-Control-Max-Age: 30
- Set-Cookie: ASP.NET_SessionId=5npqri55dl1k1zvij1tlw3re; path=/; HttpOnly
- Cache-Control: private
- Content-Length: 0
- POST /PreflightedRequests.aspx HTTP/1.1
- Host: dotnet.aspx.cc
- User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)
- Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
- Accept-Language: zh-cn,zh;q=0.5
- Accept-Encoding: gzip,deflate
- Accept-Charset: GB2312,utf-8;q=0.7,*;q=0.7
- Keep-Alive: 300
- Connection: keep-alive
- POWERED-BY-MENGXIANHUI: Approve
- Content-Type: application/xml; charset=UTF-8
- Referer: http://www.meng_xian_hui.com:801/CrossDomainAjax/PreflightedRequests.html
- Content-Length: 19
- Origin: http://www.meng_xian_hui.com:801
- Pragma: no-cache
- Cache-Control: no-cache
- <root>测试</root>
- HTTP/1.x 200 OK
- Date: Sun, 10 Jan 2010 14:00:34 GMT
- Server: Microsoft-IIS/6.0
- X-Powered-By: ASP.NET
- X-AspNet-Version: 2.0.50727
- Access-Control-Allow-Origin: http://www.meng_xian_hui.com:801
- Set-Cookie: ASP.NET_SessionId=byvose45zmtbqy45d2a1jf2i; path=/; HttpOnly
- Cache-Control: private
- Content-Type: text/html; charset=utf-8
- Content-Length: 65
以上的代码反映了预检请求的执行过程:首先发送 OPTIONS 请求头,用来向服务器咨询服务器的更多信息,以便为后续的真实请求做准备。比如是否支持 POST 方法等。值得注意的是:
浏览器还发送 Access-Control-Request-Method: POST 和 Access-Control-Request-Headers: powered-by-mengxianhui 请求头。
注意:以上过程是第一次请求的时候的过程,如果在 30 秒内重复点击按钮,你可以看不到 OPTIONS 这一过程。则执行过程是这样的:
- POST /PreflightedRequests.aspx HTTP/1.1
- Host: dotnet.aspx.cc
- User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.2; zh-CN; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)
- Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
- Accept-Language: zh-cn,zh;q=0.5
- Accept-Encoding: gzip,deflate
- Accept-Charset: GB2312,utf-8;q=0.7,*;q=0.7
- Keep-Alive: 300
- Connection: keep-alive
- POWERED-BY-MENGXIANHUI: Approve
- Content-Type: application/xml; charset=UTF-8
- Referer: http://www.meng_xian_hui.com:801/CrossDomainAjax/PreflightedRequests.html
- Content-Length: 19
- Origin: http://www.meng_xian_hui.com:801
- Pragma: no-cache
- Cache-Control: no-cache
- <root>测试</root>
- HTTP/1.x 200 OK
- Date: Sun, 10 Jan 2010 14:06:32 GMT
- Server: Microsoft-IIS/6.0
- X-Powered-By: ASP.NET
- X-AspNet-Version: 2.0.50727
- Access-Control-Allow-Origin: http://www.meng_xian_hui.com:801
- Set-Cookie: ASP.NET_SessionId=qs1c4urxywdbdx55u04pvual; path=/; HttpOnly
- Cache-Control: private
- Content-Type: text/html; charset=utf-8
- Content-Length: 65
为什么会这样?细心的童鞋可能注意到了,在服务器端有一行代码 Response.AddHeader("Access-Control-Max-Age", "30"); 它是用来设置预检的有效时间的,单位是秒。这一点要特别注意。