Common cross-origin resource request analysis, cross-origin Resource

Source: Internet
Author: User

Common cross-origin resource request analysis, cross-origin Resource

Ajax technology is most often used in WEB development to complete client-to-server communication. The XmlHttpRequest object that implements Ajax communication brings about cross-domain security policy issues. Simply put, by default, an XHR object can only access resources in the same domain as the page containing it.

So the question is, what is cross-origin? In general, the second-level domain name/port number/protocol/must be the same as the page containing Ajax. Example:

Www.tangide.com access to www.i5r.com is cross-origin.
A.tangide.com access B .tangide.com is cross-origin.
Www.tangide.com: 8080 access to www.tangide.com: 8090 is cross-origin.
Http://www.tangide.com access https://www.tangide.com is cross-origin.

Although cross-origin requests may cause security issues, sometimes cross-origin request resources are also necessary. The following describes two common cross-origin methods.

1) CORS: CORS for short

The general working principle can be understood as: the page on A wants to obtain resources on B, the browser will first send a head request to get the http header of server B to determine whether Access-Control-Allow-Origin has A (based on the previous speculation)
If yes, the Browser allows cross-origin. Otherwise, the request is rejected ~

Write a test code and use Nodejs to build a simple server:

var http = require('http');var server = http.createServer(function(req, res) {     res.writeHead(200, {'Content-Type':'text/plain',                         'Access-Control-Allow-Origin':'http://www.i5r.com',                         'Access-Control-Allow-Headers':'If-Modified-Since'})    ;console.log((req.url));console.log((req.headers));res.end(JSON.stringify({code: 0, message:'ok'}));}); server.listen(8090);
The server listens to port 8090. The Access-Control-Allow-Origin option lists the origins allowed by the server for cross-origin resource requests. The Access-Control-Allow-Headers option is used to configure the header information that can be sent by the client. The If-Modified-Since option is commonly used for browser caching. When the browser sends an http request to obtain the resource, the If-Modified-Since option carries the last modification time (GMT format) of the resource file ), indicates that resources will be updated if the requested resource changes after this time point. Otherwise, the server returns a status code 304, indicating "Not Modified ". Therefore, If some resources force the browser not to cache, you can set If-Modified-Since to 0 so that resources are retrieved from the server every time.

Next, write the client test code:

<!DOCTYPE html>Code for sending an Ajax request:

funcntion testAction(action, onDone) {var info = {};info.method = 'post';info.url = 'http://www.i5r.com:8090' + action;httpSendRequest(info);}     function httpSendRequest(info) {var xhr = new window.XMLHttpRequest();if(!info || !info.url) {return false;}var url = info.url;var data= info.data;var method = info.method ? info.method : "GET";xhr.open(method, url, true);xhr.send(info.data ? info.data : null);xhr.onreadystatechange = function() {if(info.onProgress) {info.onProgress(xhr);}if(xhr.readyState === 4) {if(info.onDone) {info.onDone(true, xhr, xhr.responseText);console.log("response:" + xhr.responseText);}}console.log("onreadystatechange:" + xhr.readyState);return;};
Although the server listens on port 8090, it has added www.i5r.com to the Cross-origin permit list. Therefore, the output is normally as follows:
response:{"code":0,"message":"ok"}onreadystatechange:4 
We can modify the 'access-Control-Allow-origin': 'http: // www.i5r.com 'statement slightly. For example, the default cross-Origin request of port 8080 is supported: 'access-Control-Allow-origin': 'http: // www.i5r.com '. Refresh page: click Send request to get the following error message:

XMLHttpRequest cannot load http://www.i5r.com:8090/read.php. The 'Access-Control-Allow-Origin' header has a value 'http://www.i5r.com:8080' that is not equal to the supplied origin. Origin 'http://www.i5r.com' is therefore not allowed access.
The error message indicates the cause ~
If a server is built with express, you can configure it as follows:

app.use(function(req, res, next) {  res.header("Access-Control-Allow-Origin", "*");  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");  next();});
Here, "*" is a wildcard that allows the request source to cross-origin.

2) use JSONP to complete cross-origin resource requests. First, write the front-end test code:

The processing function directly prints the feedback after receiving the server response.

Modify the server test code:

var http = require('http');var urlParser = require('url');var server = http.createServer(function(req, res) {res.writeHead(200, {'Content-Type':'text/plain'});console.log(req.url);var query = urlParser.parse(req.url, true).query;console.log(query);if(query.callback) {var str = query.callback + "(" +JSON.stringify({code: 0, message:'ok'})+");";console.log(str);res.end(str);}else {res.end(JSON.stringify({code: 0, message:'ok'}));}});server.listen(8090);
When sending a request, the frontend adds the name of the "Callback" function to the url. when processing the request, the server directly returns the data format of the callback function to be executed, in this way, the browser will execute this function when judging that the current page has a function with the same name. In this way, a cross-origin request is completed.

Finally, it should be noted that cross-origin is restricted by browser behavior, rather than JS or DOM behavior. If you have the ability, you can develop a browser to complete cross-origin support :).

Cross-origin requests have their respective advantages and disadvantages. If you are studying similar issues, please contact us ~

References: https://github.com/drawapp8/gamebuilder/wiki/%E4%B8%AD%E6%96%87%E6%96%87%E6%A1%A3







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.