When a resource requests a resource from a different domain or port than the server on which the resource is located , The resource will initiate a Cross domain HTTP request .

For safety reasons , Browsers restrict cross domain attacks initiated from within scripts HTTP request . for example ,XMLHttpRequest  and  Fetch follow The same-origin policy . therefore , Use  XMLHttpRequest or  Fetch  Of Web The application can only HTTP The request is sent to its own domain . To improve Web Applications , Developers ask browser vendors to allow cross domain requests .

•CORS What can be done :

Normal use AJAX Cross domain issues will need to be considered normally , So great programmers have come up with a series of solutions to cross domain problems , Such as JSONP、flash、ifame、xhr2 wait .

• CORS Principle :

CORS Define a mechanism for cross domain access , It can make AJAX Achieve cross domain access .CORS Allow network applications on one domain to submit cross domain AJAX request . It's very easy to do this , Just send a response header by the server .

Now let's get down to business. The details are as follows :

cross-site HTTP request (Cross-site HTTP request) The domain of the resource that initiated the request is different from the domain of the resource that the request pointed to HTTP request .

for instance , I am here Web Website A(www.a.com) Pass through <img> The tag introduces B Station resources (www.b.com/images/1.jpg), that A The station will tell you B The station initiates a cross site request .

This kind of cross site request for image resources is allowed , Similar cross site requests include CSS file ,JavaScript Documents, etc. .

But if it's initiated in a script HTTP request , For safety reasons , Will be limited by the browser . such as , Use XMLHttpRequest Object initiation HTTP The request must be complied with The same-origin policy .

So-called “ The same-origin policy ” Refer to Web Applications can only use XMLHttpRequest Object is initiated in the domain where it originated HTTP request , The request source and the request object must be in the same domain .

for instance ,http://www.a.com, The protocol for this site is http, Domain name is www.a.com, The default port is 80. So here's the homology :

•http://www.a.com/index.html Homology

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

•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 )

In order to develop more powerful , More abundant Web application , Cross domain requests are common , So how to make cross domain requests without sacrificing security ?

W3C Recommended a new mechanism , Cross source resource sharing (Cross-Origin Resource Sharing (CORS)).

Cross source resource sharing (CORS) It's through the client + The server side cooperates to declare to ensure the security of the request . The server will be in HTTP Add a series of HTTP Request parameters ( for example Access-Control-Allow-Origin etc. ), To limit which domain requests and which request types are acceptable , The client must declare its own source when making the request (Orgin), Otherwise the server will not process , If the client doesn't make a statement , The request will even be intercepted directly by the browser, but it can't reach the server . Server received HTTP After the request, the domain will be compared , Only requests from the same domain will be processed .

A use CORS Examples of implementing 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 side :

public class Test : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
// Declare to accept requests from all domains
context.Response.AddHeader("Access-Control-Allow-Origin", "*");
context.Response.Write("Hello World");
}
public bool IsReusable
{
get
{
return false;
}
}
}

cons- More articles on cross domain requests

  1. Laravel Medium ajax Cross-domain request

    Recent contact Laravel frame ajax There are some problems in the process of cross domain request , Here is a summary . Start with ajax Please keep reporting 500 error , After searching for relevant information, we found that Laravel To allow cross domain requests to join Cors middleware , The code is as follows ...

  2. Cross-domain request ——WebClient adopt get and post request api

    AJAX Cross domain requests cannot be implemented , After special treatment . Generally, the backstage can pass WebClient Implement cross domain requests ~ //get request         string url = string.Format("htt ...

  3. Native js encapsulation ajax, Implement cross domain requests

    describe : need ajax Cross-domain request , use cors Cross domain solutions . Server settings : header('Access-Control-Allow-Origin: http://front.ls-la.me'); header ...

  4. About trial jquery Of jsonp Realization ajax Cross domain data request

    When we are in the process of development, we have to get another system data , It causes cross domain problems , This is the solution to be discussed below : Let's get familiar with json and jsonp The difference between : Use AJAX Will inevitably face two problems , The first is AJAX In what format to submit ...

  5. 【JavaScript】-- Focus on cross domain requests

    JSON JSON(JavaScript Object Notation) Is a lightweight data exchange format . JSON It's a string Javascript object , For example, it can be in django Send a JSON Format ...

  6. utilize CORS Implement cross domain requests ( Reprint )

    Cross domain request is always a difficult problem in web programming , in the past , Most people tend to use JSONP To solve this problem . But now, , We can think about it W3C It's a new feature of --CORS(Cross-Origin Resource Sh ...

  7. Ajax_05 Cross domain request for

    1. Cross-domain request : Cross Domain Request: Cross domain HTTP request , The browser accesses another resource under another domain name from a resource under one domain name ( agreement . The domain name or port number is different ): ① When browsers allow cross domain requests :  < ...

  8. Talking about linux Next , utilize Nginx Server proxy implementation ajax Cross-domain request .

    ajax Cross domain requests are used by front-end developers in almost any project , as everyone knows , There are three ways to request across domains : jsonp; XHR2 agent : jsonp: This should be the most used one in development , The most common cross domain request method , Actually aj ...

  9. solve ajax Cross-domain request ( summary )

    ajax Cross-domain request , At present, it has been realized in several ways :   1) Use native js Of xhr Object implementation .                var url="http://freegeoip.net/json/" ...

  10. 【 note 】Asp.Net WebApi Yes js POST Support scheme for cross domain requests with parameters

    Let's talk about the demand first : In the original WebApi In the project, add a pair of js Cross domain request support , Request mode : With POST Mainly ,webapi According to the requirements of the original project, the routing rules are modified as follows : public static void Register(Http ...

Random recommendation

  1. mybatis matters needing attention

    1. If the configuration is loaded with annotations CRUD Query statement , The configuration in the mapping file is : <mapper class="com.day03_mybaits.test3.UserMapper"/ ...

  2. Chrome and IE Use in window.open function

    Do front-end development personnel often meet back to use windows.open This function opens a new web window , There are some things to note when using this function , stay Chrome and IE There are some detailed differences in this function . Here's what I used in my project ...

  3. Set raspberry pie 3 B+ Static IP

    modify /etc/dhcpcd.conf  file sudo vim /etc/dhcpcd.conf interface eth0 static ip_address= static routers=192 ...

  4. Java BigDecimal Use

    // division : Accurate to 4 position BigDecimal a = new BigDecimal(1213); BigDecimal b = new BigDecimal(10302); BigDecimal rat ...

  5. [Java Pick up two ]Tomact And Http Part summary .

    Preface :   I just came back very early today , Sum up Tomcat And Http Basic knowledge of . 1, Tomcat    web Relevant concepts         web: Meaning of web page , Web resources include all resources on the server .        ...

  6. ci To configure smarty Notes

    Need to use ci To write a background configuration smarty, We can find some related articles on the Internet . But it's all old stuff , For the most part smary2.* Configuration method of . According to this configuration, there will be some errors . In fact, the configuration smary It's going to be easier . The base ...

  7. &lt;&lt; Dreambreak code &gt;&gt; Reading notes

    From any angle ,Chandler Projects start out enviable . Although it's about how a software project fails , But there's something in it that I find very interesting .  If you fail, reflect : Positioning cannot go against the trend of the times , The trend of the Internet is irreversible , Personnel communication and cooperation is the eternal goal ...

  8. Android - IOExceptionConnection to xxx refused.

    still stackoverflow I'm a foreigner , Go to google On type once , We'll find out why . In use today Apache Provided HttpClient Connect Tomcat The server , Use log When catching exceptions , The tip says :IOEx ...

  9. RESTful Web Services: A Tutorial--reference

    As REST has become the default for most Web and mobile apps, it's imperative to have the basics at y ...

  10. js Insert... At specified location html label ( Editable div)

    demo The effect is as follows : html The code part is as follows : <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" &q ...