Home > Web Front-end > JS Tutorial > body text

JS cross-domain solution using CORS to achieve cross-domain_javascript skills

WBOY
Release: 2016-05-16 15:05:33
Original
2361 people have browsed it

Introduction

Cross-domain is a question I often ask in daily interviews. This word appears frequently in the front-end world. The main reason is due to security restrictions (same origin policy, that is, JavaScript or cookies can only access the same domain) content), because we will inevitably need to perform cross-domain operations during daily project development, so cross-domain capabilities are also considered one of the basic skills of front-end engineers.

Like most cross-domain solutions, JSONP is also my choice. However, one day the PM's needs changed and a certain function needed to be changed to support POST. Because the amount of data transmitted was relatively large, the GET format could not be handled. So I tinkered with the long-famous CORS (Cross-Origin Resource Sharing), and this article is just a note and summary of the tinkering period.

•What CORS can do:

Normal use of AJAX requires normal consideration of cross-domain issues, so great programmers have come up with a series of solutions to cross-domain issues, such as JSONP, flash, ifame, xhr2, etc.

• Principle of CORS:

CORS defines a cross-domain access mechanism that allows AJAX to achieve cross-domain access. CORS allows a web application on one domain to submit cross-domain AJAX requests to another domain. Implementing this functionality is as simple as sending a response header by the server.

Let’s get down to business and the specific details are as follows:

Cross-site HTTP request (Cross-site HTTP request) refers to an HTTP request in which the domain of the resource initiating the request is different from the domain of the resource pointed to by the request.

For example, I introduced the resources of website B (www.b.com/images/1.jpg) through the tag in Web website A (www.a.com) , then station A will initiate a cross-site request to station B.

Cross-site requests for this kind of image resources are allowed. 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, using the XMLHttpRequest object to initiate an HTTP request must comply with the same origin policy.

The so-called "same origin policy" means that web applications can only use the XMLHttpRequest object to initiate HTTP requests to the domain where the origin is located. The request source and the 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 homology:

•http://www.a.com/index.html Same origin

•https://www.a.com/a.html Different sources (different protocols)

•http://service.a.com/testService/test different sources (different domain names)

•http://www.b.com/index.html Different sources (different domain names)

•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 to make cross-domain requests without giving up security?

W3C recommended a new mechanism, Cross-Origin Resource Sharing (CORS).

Cross-origin resource sharing (CORS) ensures request security 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 can be accepted, and the client must declare its own when initiating a request. Origin (Origin), otherwise the server will not process it. If the client does not make a statement, the request will even be directly intercepted by the browser and will not 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");    
// 声明请求源
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();
} 
Copy after login

Server:

public class Test : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
// 声明接受所有域的请求
context.Response.AddHeader("Access-Control-Allow-Origin", "*");
context.Response.Write("Hello World");
}
public bool IsReusable
{
get
{
return false;
}
}
}
Copy after login

Enable cross-domain access in Web API

CORS is a collaborative statement between the server and the client to ensure request security. Therefore, if you need to enable CORS in Web API, you also need to configure it accordingly. Fortunately, Microsoft's ASP.NET team provides an official solution that supports cross-domain support. You only need to add it in NuGet.

Then perform 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 配置和服务
// 将 Web API 配置为仅使用不记名令牌身份验证。
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// 允许Web API跨域访问
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);
}
}
Copy after login

由於IE10以下瀏覽器不支援CORS,因此目前在國內CORS並不是主流的跨域解決方案,但是隨著windows 10的發布,IE的逐漸衰落,可以預見,在不遠的將來CORS將成為跨域的標準解決方案。

以上所述是小編給大家介紹的JS跨域解決方案之使用CORS實現跨域,希望對大家有所幫助!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template