Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize Cross-domain Scheme through CORS in Angular

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces how Angular realizes the cross-domain solution through CORS, the content is very detailed, interested friends can refer to, hope to be helpful to you.

Take iframe as a front-end engineer. I hate things like iframe very much. It not only increases the high load on performance, but also is not easy to control.

The way to realize cross-domain in Angular application is relatively simple, basically through two ways. One is JSONP, the other is through CORS. The former is a relatively old technique, and the latter I feel a little more powerful, so I mainly talk about how Angular works with CORS across domains.

Try not to use JSONP as much as possible, which is a principle to start with Angular cross-domain. Anyway, script's tag embedding feels a bit low.

Angular advocates the separation of front and rear ends, so it is a question of which side to implement the cross-domain. It has to be said that the technical limitation of the front end is that even the relatively easy-to-use JSONP is powerless for non-GET requests, because it essentially uses script to get some resources.

The limitation of JSONP, which can only be GET, completely restricts its use in the API scenario where Angular advocates a RESTful-style interface, and we can't abandon POST and PUT. And the error handling of JSONP is very weak and unsatisfactory. In short, the front-end implementation has a variety of limitations across domains, such as document.domain, which can only be used in the case of the same primary domain but different subdomains.

So to sum up, although the front end has many ways to deal with cross-domain, but many but not sophisticated, the shortcomings are more obvious. A relatively better way is to participate in the processing through the back end, which is not only more applicable, but also the front end only needs to send a normal Ajax request. Such a technology is called CORS.

Cross-Origin Resource Sharing cross-domain resource sharing should be the most recommended cross-domain processing scheme. It is not only suitable for all kinds of Method, but also more convenient and simple. Of course, such a hanging thing is only supported by modern browsers, and don't think about the old antiques under IE8.

Principle of CORS implementation

Although cross-domain implementation through CORS is basically achieved entirely by the back end, it is a powerful front end. You still need to master this principle so that when you encounter an 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 sharing resources through HTTP, so that each requested service can return resources directly. It uses HTTP interaction to determine whether the request source is qualified to request the resource, and controls the access to the resource by setting HTTP Header.

The specific process is that the front end sends a normal request:

$http.get ('www.cros.com/api/data', {params: {name:' stubborn Shi'}})

The backend sets the header of response:

Access-Control-Allow-Origin: "*" Access-Control-Allow-Methods: "GET" Access-Control-Max-Age: "60"

Then you look at the behavior of the browser and find something interesting. The browser, without your intervention, finds that this is a cross-domain request. So instead of sending a GET request directly, it sends an OPTIONS request asking if the resource can be accessed across domains, a process we can call "pre-checking".

Then we see that OPTIONS's response returns information similar to the following:

HTTP/1.1 200 OK Date: Mon, 01 Dec 2013 01:15:39 GMT Server: Apache/2.0.61 (Unix) Access-Control-Allow-Origin: * Access-Control-Allow-Methods: GET Access-Control-Max-Age: 60 Content-Encoding: gzip Content-Length: 0 Connection: Keep-Alive Content-Type: text/text

The contents of these Access headers are added by the server backend, which tells the browser that all domains can access the resource across domains through the GET method within the next 60 seconds. Then the browser automatically sends the real GET request again and returns the corresponding result.

Note that this process is automatically implemented by the browser, which is not very good. Some header messages are set as follows:

| Access-Control-Allow-Origin: * / authorized source control Access-Control-Max-Age: / / authorized time Access-Control-Allow-Credentials: true | false / / controls whether to enable Cookie submission method with Ajax Access-Control-Allow-Methods: [,] * / / allow the HTTP Method Access-Control-Allow-Headers of the request: [,] * / / control which header can send the real request

Another area where front-end engineers need to collaborate is the delivery of cookie. By default, cookie is not passed through CORS. The general practice of forcing cookie to be added to header will also be rejected by browsers and reported an error. As seen above, a response header, Access-Control-Allow-Credentials, is added on the server side to control whether Cookie submission is allowed.

In Angular, we need to make some settings to achieve this:

$http.post (url, {withCredentials: true,...}) / / or $http ({withCredentials: true,...}) .post (...) / / or .config (function ($httpProvider) {$httpProvider.defaults.withCredentials = true;})

If it is jQuery, it should be set as follows:

$.Ajax ("www.cros.com/api/data", {type: "GET", xhrFields: {withCredentials: true}, crossDomain: true, success: function (data, status, xhr) {}})

After describing the process of CORS, find a picture on the Internet:

Classification of CORS

If you look closely at the browser's behavior, you will find that not all cross-domain requests send OPTIONS requests. Is it strange that this involves the classification of CORS, simple requests and complex requests.

The header of HTTP usually contains the following:

The value of Accept Accept-Language Content-Language Last-Event-ID Content-Type is only one of the following: application/x-www-form-urlencoded multipart/form-data text/plain

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

Only complex requests contain pre-check actions, and Access-Control-Max-Age should also affect the sending of OPTIONS requests.

So much for sharing how Angular implements cross-domain solutions through CORS. I hope the above content can be of some help and learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report