Cross-origin JS solutions use CORS to implement cross-origin and jscors
Introduction
Cross-origin is a frequently asked question in daily interviews. This word is not frequently used in the front-end industry, mainly because of security restrictions (same-origin policy, that is, JavaScript or cookies can only access content in the same domain), because cross-origin operations are inevitable during daily project development, therefore, Cross-Domain capability is also one of the basic skills of front-end engineers.
Like most cross-origin solutions, JSONP is also my choice, but the requirements of PM have changed one day, and a function needs to be changed to support POST, because the amount of data transmitted is large, and the GET form cannot be changed. So I am tossing the well-known CORS (Cross-Origin Resource Sharing, Cross-Origin Resource Sharing). This article is also a note and summary during the tossing.
• What can CORS do:
Normal use of AJAX requires consideration of cross-origin issues, so great programmers have developed a series of cross-origin solutions, such as JSONP, flash, ifame, and xhr2.
• Principle of CORS:
CORS defines a cross-origin access mechanism that enables AJAX to implement cross-origin access. CORS allows network applications in one domain to submit cross-origin AJAX requests to another domain. This function is very simple. You only need to send a response header by the server.
The details of this step are as follows:
Cross-site HTTP request refers to the HTTP request in which the requested resource is located in a different domain than the resource to which the request is directed.
For example, if I use the label to introduce resources of site B (www. B .com/images/1.jpg) in website A (www.a.com), site A will initiate A cross-site request to Site B.
Cross-Site requests for such image resources are allowed. For example, cross-site requests include CSS files and JavaScript files.
However, if an HTTP request is initiated in the script, it will be restricted by the browser for security reasons. For example, to use an XMLHttpRequest object to initiate an HTTP request, the same-origin policy must be followed.
The so-called "same-origin policy" means that a Web application can only use the XMLHttpRequest object to initiate an HTTP request to the origin domain. The request source and request object must be in the same domain.
For example, http://www.a.com, the protocol for this URL is http, the domain name is www.a.com, and the default port is 80. The following is the same source:
• Http://www.a.com/index.html Source
• Different https://www.a.com/a.html sources (different protocols)
• The http://service.a.com/testService/test is different from the same source (different domain names)
• The http://www. B .com/index.html is different from the same source (different domain names)
• Http://www.a.com: 8080/index.html different from the same source (different ports)
In order to develop more powerful and richer Web applications, cross-origin requests are very common. How can we make cross-origin requests without sacrificing security?
W3C recommends a new mechanism, Cross-source Resource Sharing (CORS )).
Cross-source Resource Sharing (CORS) ensures request security through the client + server collaboration statement. The server will add a series of HTTP request parameters (such as Access-Control-Allow-Origin) in the HTTP request header to restrict the requests in which domains and request types are acceptable, the client must declare its own source (Orgin) when initiating a request. Otherwise, the server will not process the request. If the client does not declare it, the request may not even be directly intercepted by the browser. After the server receives the HTTP request, it compares the domain. Only requests in the same domain are processed.
An example of cross-origin requests using CORS:
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 to accept the request context of all domains. response. addHeader ("Access-Control-Allow-Origin", "*"); context. response. write ("Hello World");} public bool IsReusable {get {return false ;}}}
Enable cross-origin access in Web APIs
CORS is a collaboration statement between the server and the client to ensure request security. Therefore, you must configure CORS in Web APIs. Fortunately, Microsoft's ASP. NET team provides an official cross-domain support solution, which only needs to be added to NuGet.
Then configure App_Start/WebApiConfig. cs to implement cross-origin access:
Public static class WebApiConfig {public static void Register (HttpConfiguration config) {// Web API configuration and service // configure the Web API to use only an anonymous token for authentication. Config. suppressDefaultHostAuthentication (); config. filters. add (new HostAuthenticationFilter (OAuthDefaults. authenticationType); // Web API route config. mapHttpAttributeRoutes (); config. routes. mapHttpRoute (name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new {id = RouteParameter. optional}); // 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 earlier than IE10 do not support CORS, CORS is currently not a mainstream cross-origin solution in China. However, with the release of windows 10, IE gradually declines and is foreseeable, in the near future, CORS will become a standard cross-origin solution.
The above section describes how to use CORS to implement cross-origin in the JS cross-origin solution. I hope it will help you!
Articles you may be interested in:
- Configure CORS instances in Apache
- Summary of several methods for implementing cross-origin in js (image ping, JSONP, and CORS)