Detailed explanation of cross-origin request methods using Ajax (XMLHttpRequest) (2)

Source: Internet
Author: User

Note: The following code should be tested in Firefox 3.5, chrome 3.0, and Safari 4. The implementation method of IE8 is different from that of other browsers.

 

2. Pre-check request

Precheck requests first need to send an http options request header to the resources of another domain name to determine whether the actually sent request is safe. Pre-check is required in the following two cases:
A is not a simple request above. For example, a POST request whose content-type is application/XML or text/XML
B. Set custom headers in requests, such as X-JSON and X-MENGXIANHUI.

Note: To test in IIS, you must configure the. aspx extension action in "application extension" to allow options.

The following is a pre-check request:

<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" <br/> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <br/> <HTML xmlns = "http://www.w3.org/1999/xhtml"> <br /> <pead> <br/> <title> Meng xianhui Ajax cross-origin request test </title> <br/> </pead> <br/> <body> <br/> <input type = 'button 'value = 'start testing 'onclick = 'crossdomainrequest () '/> <br/> <Div id = "content"> </div> <br/> <MCE: Script Type = "text/JavaScript"> <! -- <Br/> var xhr = new XMLHttpRequest (); <br/> var url = 'HTTP: // DOTNET. aspx. CC/preflightedrequests. aspx '; <br/> function crossdomainrequest () {<br/> document. getelementbyid ("content "). innerhtml = "Start request ...... "; <Br/> If (xhr) {<br/> var xml =" <root> test </root> "; <br/> xhr. open ('post', URL, true); <br/> xhr. setRequestHeader ("POWERED-BY-MENGXIANHUI", "approve"); <br/> xhr. setRequestHeader ("Content-Type", "application/XML"); <br/> xhr. onreadystatechange = handler; <br/> xhr. send (XML); <br/>}else {<br/> document. getelementbyid ("content "). innerhtml = "XMLHttpRequest cannot be created. "; <Br/>}< br/> function handler (evtxhr) {<br/> If (xhr. readystate = 4) {<br/> If (xhr. status = 200) {<br/> var response = xhr. responsetext; <br/> document. getelementbyid ("content "). innerhtml = "Result:" + response; <br/>} else {<br/> document. getelementbyid ("content "). innerhtml = "cross-access is not allowed. "; <Br/>}< br/> else {<br/> document. getelementbyid ("content "). innerhtml + = "<br/> execution status readystate:" + xhr. readystate; <br/>}< br/> // --> </MCE: SCRIPT> <br/> </body> <br/> </ptml>

 

 

In the above example we are sending XML-format data and sending a non-standard HTTP header POWERED-BY-MENGXIANHUI to demonstrate how the server should set the response header.

On the server side, the content of preflightedrequests. aspx is as follows:

<% @ Page Language = "C #" %> <br/> <MCE: script runat = "server"> <! -- <Br/> protected void page_load (Object sender, eventargs e) <br/>{< br/> If (request. httpmethod. equals ("get") <br/>{< br/> response. write ("this page is used to test cross-origin POST requests, and direct browsing is of little significance. "); <Br/>}< br/> else if (request. httpmethod. equals ("options") <br/>{< br/> // notify the client to allow precheck requests. And set the cache time <br/> response. clearcontent (); <br/> response. addheader ("access-control-allow-origin", "http://www.meng _ xian_hui.com: 801"); <br/> response. addheader ("access-control-allow-methods", "post, get, Options"); <br/> response. addheader ("access-control-allow-headers", "POWERED-BY-MENGXIANHUI"); <br/> response. addheader ("access-control-max-Age", "30"); <br/> // No data is returned during this process <br/> response. end (); <br/>} <Br/> else if (request. httpmethod. equals ("Post") <br/>{< br/> If (request. headers ["Origin"]. equals ("http://www.meng _ xian_hui.com: 801") <br/>{< br/> system. XML. xmldocument Doc = new system. XML. xmldocument (); <br/> Doc. load (request. inputstream); <br/> response. addheader ("access-control-allow-origin", "http://www.meng _ xian_hui.com: 801"); <br/> response. write ("the data you submitted is: <br/>" + server. htmlenc Ode (Doc. outerxml); <br/>}< br/> else <br/>{< br/> response. Write ("your website request is not allowed. "); <Br/>}< br/> // --> </MCE: SCRIPT>

 

Click the start test button to execute the following requests.

Options/preflightedrequests. aspx HTTP/1.1 <br/> HOST: DOTNET. aspx. CC <br/> 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) <br/> Accept: text/html, application/XHTML + XML, application/XML; q = 0.9 ,*/*; Q = 0.8 <br/> Accept-language: ZH-CN, ZH; q = 0.5 <br/> Accept-encoding: gzip, deflate <br/> Accept-charset: gb2312, UTF-8; q = 0.7, *; q = 0.7 <br/> keep-alive: 300 <br/> connection: keep-alive <br/> origin: http://www.meng _ xian_hui.com: 801 <br/> access-control-request-method: Post <br/> access-control-request-headers: powered-by-mengxianhui <br/> HTTP/1.x 200 OK <br/> date: Sun, 10 Jan 2010 14:00:34 GMT <br/> Server: microsoft-IIS/6.0 <br/> X-powered-by: Asp. net <br/> X-ASPnet-version: 2.0.50727 <br/> access-control-allow-origin: http://www.meng _ xian_hui.com: 801 <br/> access-control-allow-Methods: Post, get, options <br/> access-control-allow-headers: POWERED-BY-MENGXIANHUI <br/> access-control-max-age: 30 <br/> set-COOKIE: Asp. net_sessionid = 5npqri55dl1k1zvij1tlw3re; Path =/; HTTPOnly <br/> cache-control: Private <br/> Content-Length: 0 <br/> post/preflightedrequests. aspx HTTP/1.1 <br/> HOST: DOTNET. aspx. CC <br/> 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) <br/> Accept: text/html, application/XHTML + XML, application/XML; q = 0.9 ,*/*; Q = 0.8 <br/> Accept-language: ZH-CN, ZH; q = 0.5 <br/> Accept-encoding: gzip, deflate <br/> Accept-charset: gb2312, UTF-8; q = 0.7, *; q = 0.7 <br/> keep-alive: 300 <br/> connection: keep-alive <br/> POWERED-BY-MENGXIANHUI: approve <br/> Content-Type: Application/XML; charset = UTF-8 <br/> Referer: http://www.meng _ xian_hui.com: 801/crossdomainajax/preflightedrequests.html <br/> Content-Length: 19 <br/> origin: http://www.meng _ xian_hui.com: 801 <br/> Pragma: No-Cache <br/> cache-control: no-Cache <br/> <root> test </root> <br/> HTTP/1.x200 OK <br/> date: Sun, 10 Jan 2010 14:00:34 GMT <br/> server: Microsoft-IIS/6.0 <br/> X-powered-by: Asp. net <br/> X-ASPnet-version: 2.0.50727 <br/> access-control-allow-origin: http://www.meng _ xian_hui.com: 801 <br/> set-COOKIE: Asp. net_sessionid = byvose45zmtbqy45d2a1jf2i; Path =/; HTTPOnly <br/> cache-control: Private <br/> Content-Type: text/html; charsets = UTF-8 <br/> Content-Length: 65

 

The above Code reflects the execution process of the pre-check request: First, send the options request header to consult the server for more information, so as to prepare for subsequent real requests. For example, whether the POST method is supported. It is worth noting that:

The browser also sends the access-control-request-method: Post and access-control-request-headers: powered-by-mengxianhui request headers.

Note: The above process is the first request. If you click the button again within 30 seconds, you cannot see the Options Process. The execution process is as follows:

Post/preflightedrequests. aspx HTTP/1.1 <br/> HOST: DOTNET. aspx. CC <br/> 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) <br/> Accept: text/html, application/XHTML + XML, application/XML; q = 0.9 ,*/*; Q = 0.8 <br/> Accept-language: ZH-CN, ZH; q = 0.5 <br/> Accept-encoding: gzip, deflate <br/> Accept-charset: gb2312, UTF-8; q = 0.7, *; q = 0.7 <br/> keep-alive: 300 <br/> connection: keep-alive <br/> POWERED-BY-MENGXIANHUI: approve <br/> Content-Type: Application/XML; charset = UTF-8 <br/> Referer: http://www.meng _ xian_hui.com: 801/crossdomainajax/preflightedrequests.html <br/> Content-Length: 19 <br/> origin: http://www.meng _ xian_hui.com: 801 <br/> Pragma: No-Cache <br/> cache-control: no-Cache <br/> <root> test </root> <br/> HTTP/1.x200 OK <br/> date: Sun, 10 Jan 2010 14:06:32 GMT <br/> server: Microsoft-IIS/6.0 <br/> X-powered-by: Asp. net <br/> X-ASPnet-version: 2.0.50727 <br/> access-control-allow-origin: http://www.meng _ xian_hui.com: 801 <br/> set-COOKIE: Asp. net_sessionid = qs1c4urxywdbdx55u04pvual; Path =/; HTTPOnly <br/> cache-control: Private <br/> Content-Type: text/html; charsets = UTF-8 <br/> Content-Length: 65

 

Why? Careful kids shoes may notice that there is a line of code response on the server side. addheader ("access-control-max-Age", "30"); it is used to set the validity period of the pre-check, in seconds. Pay special attention to this.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.