需要特别注意的是:在请求信息中,浏览器使用 Origin 这个 HTTP 头来标识该请求来自于 http://www.meng_xian_hui.com:801;在返回的响应信息中,使用 Access-Control-Allow-Origin 头来控制哪些域名的脚本可以访问该资源。如果设置 Access-Control-Allow-Origin:*,则允许所有域名的脚本访问该资源。如果有多个,则只需要使用逗号分隔开即可。
注意:在服务器端,Access-Control-Allow-Origin 响应头 http://www.meng_xian_hui.com:801 中的端口信息不能省略。
有人可能会想:自己发送请求头会如何呢?比如 xhr.setRequestHeader("Origin","http://www.meng_xian_hui.com:801"); 实践证明,自己设置 Origin 头是不行的。
是不是现在就可以采用 XMLHttpRequest 来请求任意一个网站的数据呢?还是不行的。允许哪些域名可以访问,还需要服务器来设置 Access-Control-Allow-Origin 头来进行授权,具体的代码是:
Response.AddHeader("Access-Control-Allow-Origin", "http://www.meng_xian_hui.com:801");
这行代码就告诉浏览器,只有来自 http://www.meng_xian_hui.com:801 源下的脚本才可以进行访问。
好了,上面我们就完成了一个简单的跨域请求,怎么样?感觉还是不错的吧。下面我们进行一个“预检”请求。
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"); 它是用来设置预检的有效时间的,单位是秒。这一点要特别注意。
3,带验证信息的请求
身份验证是Web开发中经常遇到的问题,在跨域请求中,默认情况下是不发送验证信息的。要想发送验证信息,需要进行withCredentials 属性,下面就是一个简单请求的例子:
- <!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/RequestsWithCredentials.aspx';
- function crossDomainRequest() {
- document.getElementById("content").innerHTML = "开始进行请求……";
- if (xhr) {
- xhr.open('GET', url, true);
- xhr.onreadystatechange = handler;
- xhr.withCredentials = "true";
- xhr.send();
- } 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 += "<br/>执行状态 status:" + xhr.status;
- }
- }
- else {
- document.getElementById("content").innerHTML += "<br/>执行状态 readyState:" + xhr.readyState;
- }
- }
- // --></mce:script>
- </body>
- </html>
点击“开始测试”,我们可以检测到下面的请求执行过程:
- GET /RequestsWithCredentials.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
- Referer: http://www.meng_xian_hui.com:801/CrossDomainAjax/RequestsWithCredentials.html
- Origin: http://www.meng_xian_hui.com:801
- HTTP/1.x 200 OK
- Date: Sun, 10 Jan 2010 14:12:26 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-Credentials: true
- Set-Cookie: ASP.NET_SessionId=fn2zf0zq1cuwgf45fm5fw145; path=/; HttpOnly
- Set-Cookie: visit=1; expires=Sun, 10-Jan-2010 14:12:56 GMT; path=/
- Cache-Control: no-cache
- Pragma: no-cache
- Expires: -1
- Content-Type: text/html; charset=utf-8
- Content-Length: 1
从上面的响应中可以看出,Cookie 是会随请求一起发送的。如果我们多次点击测试按钮,则可以看到请求和响应的结果是这样的:
- GET /RequestsWithCredentials.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
- Referer: http://www.meng_xian_hui.com:801/CrossDomainAjax/RequestsWithCredentials.html
- Origin: http://www.meng_xian_hui.com:801
- Cookie: ASP.NET_SessionId=fn2zf0zq1cuwgf45fm5fw145; visit=2
- HTTP/1.x 200 OK
- Date: Sun, 10 Jan 2010 14:13:58 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-Credentials: true
- Set-Cookie: visit=3; expires=Sun, 10-Jan-2010 14:14:28 GMT; path=/
- Cache-Control: no-cache
- Pragma: no-cache
- Expires: -1
- Content-Type: text/html; charset=utf-8
- Content-Length: 1
注意 Cookie: ASP.NET_SessionId=fn2zf0zq1cuwgf45fm5fw145; visit=2 这一行,访问计数器已经被一起发送到服务器。
4,IE8 中的实现方法
IE8已经开始支持跨域访问资源了,但是,IE8提供的功能还比较简单,可以进行简单的请求,下面是一个使用的例子:
- <!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 XDomainRequest();
- var url = 'http://dotnet.aspx.cc/SimpleCrossSiteRequests.aspx';
- function crossDomainRequest() {
- document.getElementById("content").innerHTML = "开始……";
- if (xhr) {
- xhr.open('GET', url);
- xhr.onload = handler;
- xhr.send();
- } else {
- document.getElementById("content").innerHTML = "不能创建 XDomainRequest";
- }
- }
- function handler(evtXHR) {
- document.getElementById("content").innerHTML = "结果:" + xhr.responseText;
- }
- // --></mce:script>
- </body>
- </html>
另外,IE8的实现方法与其他浏览器不同。更多内容请参考 XDomainRequest 对象,地址是:
http://msdn.microsoft.com/zh-cn/library/cc288060(VS.85).aspx
最后,愿意测试的朋友可以访问这个 http://dotnet.aspx.cc/SimpleCrossSiteRequests.aspx 地址进行“简单请求”的测试,本页面允许任何地址进行跨域访问。(不好意思,个人网站可能被河蟹了)