What is Cors?
CORS is a W3C standard, which stands for "Cross-origin resource sharing". It allows the browser to make XMLHttpRequest requests to cross-origin servers, thus overcoming the limitation that AJAX can only be used homogeneously.
1. Introduction
CORS requires both browser and server support. Currently, all browsers support this feature, and IE browser cannot be lower than IE10.
The entire CORS communication process is completed automatically by the browser and does not require user participation. For developers, CORS communication is no different from homologous AJAX communication, and the code is exactly the same. Once the browser finds that an AJAX request crosses the source, it will automatically add some additional header information, and sometimes one more additional request, but the user will not feel it.
Therefore, the key to achieving CORS communication is the server. As long as the server implements the CORS interface, it can communicate across sources.
In fact, web server programs (such as ASP.NET or PHP, etc.) cannot distinguish and will not manage whether an incoming Http request is a cross-domain Ajax request.CORS is designed to solve this problem, and the W3C custom CORS standard gives browsers a mechanism to allow Ajax cross-domain requests.
2: Native JS Ajax request code
Since I don't want to reference jQuery, I encapsulated the following methods with js, as follows:
Ajax requests interface tests and finds an error as follows:
Three: Set a controller method to allow cross-domain
So soAll are allowedThe controller or API method is cross-domain, in the web.config filesystem.webServerThe following configuration is added under the node:
The above is not the result we wanted! If we want to allow only a domain name to access one of our interfaces across domains, we need to define a feature that looks like this:
The code for setting cross-domain access permissions is this paragraph HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", origin);
We set the characteristics on top of the controller method as follows:
We initiate the Ajax request again with the result as shown below:
API interface resources from our other websites can be successfully accessed.
(End)
|