ITPub博客

首页 > Linux操作系统 > Linux操作系统 > AJAX(XMLHttpRequest)进行跨域请求方法详解(二)

AJAX(XMLHttpRequest)进行跨域请求方法详解(二)

原创 Linux操作系统 作者:孟子E章 时间:2010-01-11 09:15:54 0 删除 编辑
2,预检请求

预检请求首先需要向另外一个域名的资源发送一个 HTTP OPTIONS 请求头,其目的就是为了判断实际发送的请求是否是安全的。下面的2种情况需要进行预检:
a,不是上面的简单请求,比如使用Content-Type 为 application/xml 或 text/xml 的 POST 请求
b,在请求中设置自定义头,比如 X-JSON、X-MENGXIANHUI 等


注意:在 iis 里进行测试,必须在“应用程序扩展”里面配置 .aspx 扩展的动作允许 OPTIONS。

下面我们举一个预检的请求:

  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


孟宪会之AJAX跨域请求测试


 
 

 
  //  var xhr = new XMLHttpRequest();
  var url = 'http://dotnet.aspx.cc/PreflightedRequests.aspx';
  function crossDomainRequest() {
    document.getElementById("content").innerHTML = "开始进行请求……";
    if (xhr) {
      var xml = "测试";
      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 += "
执行状态 readyState:" + xhr.readyState;
    }
  }
  //]]>





上面的例子我们发送 xml 格式的数据,并且,发送一个非标准的HTTP头 POWERED-BY-MENGXIANHUI 来说明服务器端该如何设置响应头的。

在服务器端,PreflightedRequests.aspx 的内容如下:

<%@ Page Language="C#" %>

  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("您提交的数据是:

" + Server.HtmlEncode(doc.OuterXml));
      }
      else
      {
        Response.Write("不允许你的网站请求。");
      }
    }
  }




点击“开始测试”按钮,将会执行下面的一系列请求。

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
测试

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
测试

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");  它是用来设置预检的有效时间的,单位是秒。这一点要特别注意。

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/15723462/viewspace-624783/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
暂无介绍

注册时间:2008-09-03

  • 博文量
    16
  • 访问量
    456806