introduction
Cross-domain is a question I often ask in daily interviews. This term appears frequently in the front-end world. The main reason is that it is due to security restrictions (same-original strategy, that is, JavaScript or cookies can only access content under the same domain). Because we inevitably need to perform cross-domain operations during daily project development, cross-domain capabilities are also one of the basic skills of front-end engineers.
Like most cross-domain solutions, JSONP is also my choice, but one day the PM needs changed, and a certain function needs to be changed to support POST, because the amount of data transmitted is relatively large, and the GET form cannot be handled. So I have been struggling with the long-known CORS (Cross-Origin Resource Sharing), and the article here is a brief notation and summary during the struggling period.
•What can CORS do:
Normal use of AJAX requires normal consideration of cross-domain issues, so great programmers have also struggled with solutions to cross-domain problems, such as JSONP, flash, ifame, xhr2, etc.
• The principle of CORS:
CORS defines a mechanism for cross-domain access, which allows AJAX to achieve cross-domain access. CORS allows network applications on one domain to submit cross-domain AJAX requests to another domain. Implementing this function is very simple, just send a response header by the server.
Let's get to the topic below for details as follows:
Cross-site HTTP request refers to an HTTP request in which the domain where the resource initiates the request is located is different from the domain where the resource initiates the request.
For example, if I introduce the resources of B station (www.b.com/images/1.jpg) through the <img> tag in the Web site A (www.a.com), then Station A will initiate a cross-site request to Station B.
Cross-site requests for this kind of image resource are allowed, and similar cross-site requests include CSS files, JavaScript files, etc.
However, if an HTTP request is initiated in a script, it will be restricted by the browser for security reasons. For example, to initiate HTTP requests using the XMLHttpRequest object, you must comply with the same-origin policy.
The so-called "same-origin policy" means that a web application can only use the XMLHttpRequest object to initiate HTTP requests to the domain where the origin is. This request source and request object must be in the same domain.
For example, http://www.a.com, the protocol of this website is http, the domain name is www.a.com, and the default port is 80. Then the following is its homologous situation:
•http://www.a.com/index.html Homogen
•https://www.a.com/a.html Different sources (different protocols)
•http://service.a.com/testService/test Different sources (domain names are different)
•http://www.b.com/index.html Different sources (domain names are different)
•http://www.a.com:8080/index.html Different sources (different ports)
In order to develop more powerful and richer web applications, cross-domain requests are very common. So how do you make cross-domain requests without giving up security?
W3C recommends a new mechanism, namely Cross-Origin Resource Sharing (CORS).
Cross-origin resource sharing (CORS) ensures the security of requests through client + server collaborative declaration. The server will add a series of HTTP request parameters (such as Access-Control-Allow-Origin, etc.) to the HTTP request header to limit which domain requests and which request types are acceptable. The client must declare its own source (Orgin) when initiating a request, otherwise the server will not process it. If the client does not declare, the request will even be directly intercepted by the browser and cannot reach the server. After receiving the HTTP request, the server will compare the domains, and only requests from the same domain will be processed.
An example of using CORS to implement cross-domain requests:
Client:
function getHello() {var xhr = new XMLHttpRequest();xhr.open("post", "http://b.example.com/Test.ashx", true);xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // Declare the request source xhr.setRequestHeader("Origin", "http://a.example.com");xhr.onreadystatechange = function () {if (xhr.readyState == 4 && xhr.status == 200) {var responseText = xhr.responseText;console.info(responseText);}}xhr.send();}Server:
public class Test : IHttpHandler{public void ProcessRequest(HttpContext context){context.Response.ContentType = "text/plain";// Declare accepting requests from all domains context.Response.AddHeader("Access-Control-Allow-Origin", "*");context.Response.Write("Hello World");}public bool IsReusable{get{return false;}}}Enable cross-domain access in the Web API
CORS is a server-side and client collaboration statement to ensure the security of requests. Therefore, if you need to enable CORS in the Web API, you also need to configure it accordingly. Fortunately, Microsoft's ASP.NET team provides an official cross-domain-enabled solution, which only needs to be added in NuGet.
Then use the following configuration in App_Start/WebApiConfig.cs to achieve cross-domain access:
public static class WebApiConfig{public static void Register(HttpConfiguration config){// Web API Configuration and Services // Configure the Web API to use bearer token authentication only. config.SuppressDefaultHostAuthentication();config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));// Web API routing config.MapHttpAttributeRoutes();config.Routes.MapHttpRoute(name: "DefaultApi",routeTemplate: "api/{controller}/{id}",defaults: new { id = RouteParameter.Optional });// Allow Web API cross-domain access EnableCrossSiteRequests(config);config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));}private static void EnableCrossSiteRequests(HttpConfiguration config) {var cors = new EnableCorsAttribute(origins: "*",headers: "*",methods: "*");config.EnableCors(cors);}}Since browsers below IE10 do not support CORS, CORS is not a mainstream cross-domain solution in China at present. However, with the release of Windows 10 and the gradual decline of IE, it can be foreseeable that CORS will become a cross-domain standard solution in the near future.
The above is the JS cross-domain solution introduced by the editor to you. I hope it will be helpful to you!