JS cross-domain solution uses cors to implement Cross-domain _javascript techniques

Source: Internet
Author: User
Tags static class

Introduction

Cross-Domain is a question that I often ask in everyday interviews, the word's frequency is not low in the front-end world, mainly because of security restrictions (homology policy, that is, JavaScript or cookies can only access the content under the same domain), because we will inevitably need to do cross-domain operations in our daily project development. So Cross-domain ability is also regarded as one of the basic skills of front-end engineers.

Like most Cross-domain solutions, JSONP is also my choice, but one day PM needs change, a function needs to be changed to support post, because the amount of data transferred is larger, get form uncertain. So toss the next well-known cors (Cross-domain resource sharing, cross-origin Resource sharing), this article is also the small sum of tossing and summing.

What cors can do:

Normal use of Ajax will require the normal consideration of cross-domain issues, so the great program members have to toss out a series of cross-domain problem solutions, such as JSONP, Flash, Ifame, XHR2 and so on.

The principle of cors:

Cors defines a mechanism for cross-domain access that enables Ajax to implement Cross-domain access. CORS allows network applications on one domain to submit Cross-domain AJAX requests to another domain. This is a simple function to send a response header to the server.

Let's step into the details below:

A cross-station HTTP request (Cross-site) is an HTTP request that has the same domain as the resource in which the request originated, unlike the same domain as the resource to which the request is directed.

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

Cross-site requests for this kind of picture resources are allowed, similar cross-site requests include CSS files, JavaScript files, and so on.

However, if you are launching an HTTP request in a script, you will be restricted by the browser for security reasons. For example, using a XMLHttpRequest object to initiate an HTTP request must conform to the homology policy.

The so-called "homology policy" means that a Web application can only use the XMLHttpRequest object to initiate an HTTP request in the same domain as the origin, and that the request source and request object must be within a domain.

For example, http://www.a.com, the protocol for this URL is http, the domain name is www.a.com, and the port defaults to 80. So here's the homology of it:

http://www.a.com/index.html homology

https://www.a.com/a.html different sources (different protocol)

http://service.a.com/testservice/test different sources (domain name is different)

http://www.b.com/index.html different sources (domain name is different)

http://www.a.com:8080/index.html different sources (different ports)

Cross-domain requests are common in order to develop stronger, richer web applications, so how do you make Cross-domain requests without sacrificing security?

The Consortium recommends a new mechanism for cross source resource sharing (Cross-origin Resource sharing (CORS)).

Cross-source resource sharing (CORS) is a way to ensure that requests are secure through client + server-side collaboration declarations. The server side adds 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, and the client must declare its own source (Orgin) when initiating the request. Otherwise, the server will not be processed, if the client does not make a declaration, the request will even be blocked by the browser directly to the service side. When the server receives an HTTP request, the domain is compared, and only requests from the same domain are 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"); 
//Declaration Request Source
Xhr.setrequestheader ("Origin", "http://a.example.com");
Xhr.onreadystatechange = function () {
if (xhr.readystate = = 4 && xhr.status =) {
var responsetext = Xhr.responsetext;
Console.info (responsetext);
}
Xhr.send ();

Service side:

public class Test:ihttphandler
{public
void ProcessRequest (HttpContext context)
{context
. Response.ContentType = "Text/plain";
Declares the request context that accepts all domains
. 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 the server and client collaboration declaration to ensure that the request is secure, so if you need to enable cors in the Web API, you need to configure it accordingly. Fortunately, Microsoft's ASP.net team provides an official support Cross-domain solution, just add it to the NuGet.

You can then implement Cross-domain access with the following configuration in App_start/webapiconfig.cs:

public static class Webapiconfig
{public
static void Register (httpconfiguration config)
{
//Web API Configuration and Services
//Configure the Web APIs to use only bearer token authentication.
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}
);
Allows the Web API to access
enablecrosssiterequests (config) across domains;
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);
}

Because the IE10 below does not support cors, the current cors is not a mainstream cross-domain solution at home, but with the release of Windows 10, IE is fading, predictably, in the near future Cors will become a cross-domain standard solution.

The above is a small series to introduce the JS Cross-domain solution to the use of cors implementation across the domain, I hope to help!

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.