Cross-origin request methods using Ajax (XMLHttpRequest) (1)

Source: Internet
Author: User
Tags dotnet http authentication

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.

Cross-origin requests, as the name implies, are resources in one site to access resources on another site with different domain names. This is common. For example, you can use the style label to load external style table files, use the IMG label to load external images, use the script label to load external script files, and load font files through webfont. By default, the same-origin policy (Same Origin Policy) is used for accessing data such as document attributes by script ).

So what is a same-origin policy? If the protocols, domain names, and ports of the two pages are identical, they are the same source. The same-source policy is used to prevent access to or set the attributes of documents loaded from another address from a document or script loaded from one address. If the primary domain names of the two pages are the same, you can set the document. Domain attribute to regard them as the same source.

With the rise of Web2.0 and SNS, web applications require more and more cross-origin access requests. However, cross-origin requests in scripts are subject to security restrictions, web developers urgently need to provide a safer and more convenient cross-origin Request Method to integrate (mashup) their own web applications. One advantage of this is that requests can be distributed to different servers, reducing the pressure on a single server to increase the response speed; another advantage is that different business logic can be distributed to different servers to reduce load.

Fortunately, the cross-origin request standards have been introduced, and mainstream browsers have also achieved this standard. In the W3C Working Group, the Web Applications Working Group (Web application Working Group) released a cross-origin Resource Sharing (cross-origin resource sharing, the standard address: Unknown) Recommendation specification to solve the problem of cross-origin requests. This specification provides a safer cross-Origin data exchange method. You can access the website address provided above. It is worth noting that this specification can only be applied to API containers like XMLHttpRequest. IE8, Firefox 3.5 and later versions, Chrome browser, Safari 4, and so on have implemented the cross-origin Resource Sharing specification and can already make cross-origin requests.

Cross-origin resource sharing works by adding an HTTP header to determine which resources allow Web browsers to access the information under the domain name. However, for request methods that cause side effects of user data due to HTTP requests (especially for HTTP methods except get and some mime-type post ), this specification requires the browser to "pre-determine" the request, by sending an http options request header to ask the server about the supported methods, after obtaining the server's consent, then, use the actual HTTP Request Method to send the actual request. The server can also notify the client whether to send authentication information (such as Cookie and HTTP authentication data) along with the request.

The following example shows how cross-origin resource sharing works.

 

1. Simple request

 

What kind of request is simple? A simple request must meet the following two requirements:

A. Only get and post requests are used. The post here only includes the data type (Content-Type) sent to the server) must be one of application/X-WWW-form-urlencoded, multipart/form-data, or text/plain.

B. No custom request header is set for HTTP requests, for example, the commonly used X-JSON.

 

Use the following code for testing:

<! 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/simplecrosssiterequests. aspx '; <br/> function crossdomainrequest () {<br/> document. getelementbyid ("content "). innerhtml = "start ...... "; <Br/> If (xhr) {<br/> xhr. open ('get', URL, true); <br/> xhr. onreadystatechange = handler; <br/> xhr. send (); <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 "). inner Html = "Result:" + response; <br/>} else {<br/> document. getelementbyid ("content"). innerhtml = "cross-origin requests are not allowed. "; <Br/>}< br/> else {<br/> document. getelementbyid ("content "). innerhtml + = "<br/> execution status readystate:" + xhr. readystate; <br/>}< br/> // --> </MCE: SCRIPT> <br/> </body> <br/> </ptml>

 

Then, create crossdomainrequest. aspx on the server as follows:

<% @ Page Language = "C #" %> <br/> <MCE: script runat = "server"> <! -- <Br/> protected void page_load (Object sender, eventargs e) <br/> {<br/> response. addheader ("access-control-allow-origin", "http://www.meng _ xian_hui.com: 801"); <br/> response. write ("Meng Xian will send a congratulatory message to all of you: Your first cross-origin test is successful !!! "); <Br/>}< br/> // --> </MCE: SCRIPT>

 

Click the start test button to send the following request and response information:

 

GET/simplecrosssiterequests. 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/> Referer: http://www.meng _ xian_hui.com: 801/crossdomainajax/simplecrosssiterequests.html <br/> origin: http://www.meng _ xian_hui.com: 801 <br/> HTTP/1.x 200 OK <br/> date: Sun, 10 Jan 2010 13:52:00 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 = wk5v5nrs5wbfi4rmpjy2jujb; Path =/; HTTPOnly <br/> cache-control: Private <br/> Content-Type: text/html; charsets = UTF-8 <br/> Content-Length: 84

In the request information, the browser uses the origin HTTP header to identify the request from the http://www.meng _ xian_hui.com: 801; in the Response Message returned, use the access-control-allow-origin header to control which domain scripts can access the resource. If access-control-allow-origin: * is set, scripts for all domain names are allowed to access the resource. If there are multiple, separate them with commas.

Note: on the server side, port information in the access-control-allow-origin Response Header http://www.meng _ xian_hui.com: 801 cannot be omitted.

Some may think: what will happen to the request header? For example, xhr. setRequestHeader ("Origin", "http://www.meng _ xian_hui.com: 801"); Practice has proved that you can not set the origin header.

Can XMLHttpRequest be used to request data from any website now? Still not. Which domain names can be accessed? The server needs to set the access-control-allow-origin header for authorization. The specific code is as follows:

Response. addheader ("access-control-allow-origin", "http://www.meng _ xian_hui.com: 801 ");

This line of code tells the browser that only scripts from the http://www.meng _ xian_hui.com: 801 source can be accessed.

Now, we have completed a simple cross-origin request. How can this problem be solved? It feels good. Next we will make a "pre-check" request.

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.