Common cross-domain resource request analysis

Source: Internet
Author: User

Ajax technology is most commonly used during web development to accomplish client-server communication. The XMLHttpRequest object that implements Ajax communication brings about cross-domain security policy issues. Simply put, by default, the XHR object can only access resources that are located under the same domain as the page that contains it.

So the question is, what is a cross-domain? In general, the address that Ajax points to, the level two domain name/port number/protocol/must be the same as the page that contains it. Give me a chestnut:

www.tangide.com Access www.i5r.com is a cross-domain.
a.tangide.com Access b.tangide.com is a cross-domain.
www.tangide.com:8080 Access www.tangide.com:8090 is a cross-domain.
http://www.tangide.com Access https://www.tangide.com is a cross-domain.

Cross-domain may pose some security concerns, but it is sometimes necessary to request resources across domains. The two common cross-domain methods are described below.

1) CORS: referred to as cross-domain resource sharing

The approximate working principle can be understood as: A page wants to get the resources on B, the browser will first send a head request to get the HTTP header of the B server to determine if Access-control-allow-origin has a (based on the previous chestnut speculation)
If any, the browser allows cross-domain, otherwise deny ~

Simply write a test code, first build a simple server with Nodejs:

var http = require (' http '); var server = Http.createserver (function (req, res) {     Res.writehead ($, {' 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 on port 8090. The Access-control-allow-origin option lists origin where the server allows cross-domain resource requests. The Access-control-allow-headers option configures header information that is allowed to be sent by the client. The if-modified-since option is more commonly used, primarily for browser caching. When the browser sends an HTTP request for a resource, the If-modified-since option takes the last modified time in the resource file (GMT format), indicating that the resource is updated if the requested resource changes from this point in time. Otherwise the server returns a 304 status code indicating "not Modified". So if you have some resources to force the browser not to cache, you can set If-modified-since to 0 so that each time you get a resource from the server.

Next, write the client test code:

<! DOCTYPE html>
Send the relevant code for the AJAX request:

Funcntion testaction (Action, ondone) {var info = {};info.method = ' post '; info.url = ' http://www.i5r.com:8090 ' + action;htt Psendrequest (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;};
While the server is listening on port 8090, it has added www.i5r.com to the cross-domain allow list so, normally the output is as follows:
We can make a little change to the phrase ' access-control-allow-origin ': ' http://www.i5r.com ', such as a cross-domain request that supports 8080 ports by default: ' Access-control-allow-origin ': ' http://www.i5r.com '. Refresh page: Click Send Request, you will 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 ' which is not equal to the supplied Origin. Origin ' http://www.i5r.com ' is therefore not allowed access.
The error message already explains why ~
If the server is built with Express, it can be configured 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 ();});
The "*" Here is a wildcard, which means that the requested source is allowed to cross the domain.

2) using JSONP to complete cross-domain resource requests, first write the front-end test code:

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

To modify the server test code:

var http = require (' http '); var urlparser = require (' URL '); var server = Http.createserver (function (req, res) {Res.writehea D ($, {' 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);
The front end adds the name of the callback function to the URL after the request is sent, and the server directly returns the data format that needs to execute the callback function when processing the request, so that the browser executes the function when judging the current page with the same name function. This completes a cross-domain request.

Finally, it is necessary to note that the restriction of cross-domain is the behavior of the browser, not the behavior of JS or DOM, if you have the ability to develop a browser to complete cross-domain support:).

Cross-domain request different ways each have pros and cons, if you are also studying similar problems, Welcome to Exchange ~

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







Common cross-domain resource request analysis

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.