Angular uses CORS to implement cross-origin Solutions

Source: Internet
Author: User

Angular uses CORS to implement cross-origin Solutions

In the past, there was a very old article on the Internet, including the keyword "cross-origin summary and solution for Baidu" now, the first few recommendations were "Javascript cross-origin summary and solution ". after reading it, I felt that the method was a little outdated. Some of them were documents. domain and iframe solutions are somewhat "ugly" and do not feel suitable for some projects.

Taking iframe as a front-end engineer, I hate iframe, which not only increases the performance load, but also is difficult to control.

It is relatively simple to implement cross-origin in Angular applications, basically in two ways. one is JSONP, and the other is through CORS. the former is a relatively old method, and I feel a little more powerful, so this article mainly describes how Angular works with CORS.

Try not to use JSONP if possible. This is a principle that begins with Angular cross-origin. In any case, the label embedding feeling of the script is still low.‍‍

Angular advocates frontend and backend separation, so which side implements cross-origin is a problem. this has to be said the limitations of the front-end technology. Even a relatively useful JSONP is powerless for non-GET requests, because it basically uses scripts to get some resources.

JSONP can only GET restrictions. In the API scenario where Angular advocates RESTful APIs, it completely restricts the use of JSONP and PUT APIs. in addition, JSONP's error handling is weak and unsatisfactory. in short, front-end cross-domain implementation has various limitations, such as document. domain can only be used when the primary domain is the same and the subdomain is different.

To sum up, although the front-end can handle cross-origin requests in multiple ways, there are many but not precise, and the disadvantages are obvious. A better way is to participate in processing through the backend. This method is not only more adaptable, but also requires the front end to send normal Ajax requests. this technology is called CORS.

Cross-Origin Resource Sharing is the most recommended Cross-Origin processing solution. not only applicable to various methods, but also more convenient and simple. of course, only modern browsers support such hanging things, and IE8's old antiques will be skipped.

CORS implementation principle

Although cross-origin through CORS is basically implemented by the backend, it is a powerful front-end. you still need to master this principle so that when you encounter unreliable backend, it will not... you know

The essence of CORS allows the server to share resources by adding a response header Access-Control-Allow-Origin and allowing each requested service to directly return resources. it uses HTTP interaction to determine whether the request source is eligible to request the resource, and sets the HTTP Header to control the resource access permissions.

The specific process is as follows:

 
 
  1. $ Http. get ('www .cros.com/api/data', parameter params :{
  2. Name: 'stubborn Shi'
  3. }})

Set the response header at the backend:

 
 
  1. Access-Control-Allow-Origin: "*" 
  2. Access-Control-Allow-Methods: "GET" 
  3. Access-Control-Max-Age: "60"   

Then you can observe the browser's behavior and find it interesting. Without your intervention, the browser finds that this is a cross-origin request. therefore, instead of sending a GET request directly, it sends an OPTIONS request asking if the resource can be accessed across domains. This process can be called "pre-check ".

Then we can see that the response of OPTIONS returns information similar to the following:

 
 
  1. HTTP/1.1 200 OK  
  2.  
  3.  
  4. Date: Mon, 01 Dec 2013 01:15:39 GMT  
  5. Server: Apache/2.0.61 (Unix)  
  6. Access-Control-Allow-Origin: *  
  7. Access-Control-Allow-Methods: GET  
  8. Access-Control-Max-Age: 60  
  9. Content-Encoding: gzip  
  10. Content-Length: 0  
  11. Connection: Keep-Alive  
  12. Content-Type: text/text  

The content of these Access headers is added to the backend of the server. It tells the browser that in the next 60 seconds, all the domains can Access the resource through the GET method. then the browser automatically resends the real GET request and returns the corresponding result.

Note that this process is automatically implemented by the browser. Is this great? Some header information settings are as follows:

 
 
  1. Access-Control-Allow-Origin: <origin> | * // authorized source Control
  2. Access-Control-Max-Age: <delta-seconds> // authorization time
  3. Access-Control-Allow-Credentials: true | false // determines whether to enable Cookie submission with Ajax.
  4. Access-Control-Allow-Methods: <method> [, <method>] * // HTTP Method that allows the request
  5. Access-Control-Allow-Headers: <field-name> [, <field-name>] * // Control which Headers can send real requests

Another thing that requires collaboration between front-end engineers is cookie transfer. By default, CORS is used to prevent cookie transfer. generally, adding a cookie to the header is forbidden by the browser and an error is reported. as shown above, the server adds a response header, Access-Control-Allow-Credentials, to Control whether to Allow Cookie submission.

In Angular, we need to make some settings for the purpose:

 
 
  1. $ Http. post (url, {withCredentials: true ,...})
  2. // Or
  3. $ Http ({withCredentials: true,...}). post (...)
  4. // Or
  5. . Config (function ($ httpProvider ){
  6. $ HttpProvider. defaults. withCredentials = true;
  7. }

If it is jQuery, you need to set it as follows:

 
 
  1. $.ajax("www.cros.com/api/data", {  
  2.   type: "GET",  
  3.   xhrFields: {  
  4.     withCredentials: true 
  5.   },  
  6.   crossDomain: true,  
  7.   success: function(data, status, xhr) {  
  8.   }  
  9. }); 

After the CORS process is described, find an image on the Internet:

CORS Classification

If you carefully observe the browser behavior, you will find that not all cross-origin requests will send the OPTIONS request. Isn't it strange? This involves the CORS classification, simple requests, and complex requests.

The HTTP header usually contains the following content:

 
 
  1. Accept
  2. Accept-Language
  3. Content-Language
  4. Last-Event-ID
  5. The value of Content-Type is only one of the following:
  6. Application/x-www-form-urlencoded
  7. Multipart/form-data
  8. Text/plain

The HTTP method is one of HEAD, GET, and POST, and the HTTP header contains as shown above. any request that does not meet these two requirements is a complex request. for example, sending PUT, DELETE, and other HTTP actions, or Content-Type: application/json Content.

Only complex requests include the "pre-check" action. In addition, Access-Control-Max-Age should also affect the sending of OPTIONS requests.

Related Article

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.