Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create cross-domain request?

How to create a cross-domain request using Angular 2?

Can you provide an example?
Like a request between localhost:3000 and localhost:8000 cross-domain

like image 636
Ignat Avatar asked Jan 14 '16 12:01

Ignat


People also ask

How do you cross domain?

To auto link my domains, I select more settings in Google Tag Manager. Then, I navigate to the Cross Domain Tracking drop down. In the auto-linking field, I enter each of my domains in a comma-separated string. After I double-check my settings, I can save my progress to enable my changes.

What is cross domain request in JavaScript?

Cross-Domain JavaScript Requests allow developers to work around security restrictions that would prevent an application from contacting Places (Search) API directly. For example, certain location information might not be retrievable without enabling this method.


1 Answers

In fact, there is nothing to do in Angular2 regarding cross domain requests. CORS is something natively supported by browsers. This link could help you to understand how it works:

  • http://restlet.com/blog/2015/12/15/understanding-and-using-cors/
  • http://restlet.com/blog/2016/09/27/how-to-fix-cors-problems/

To be short, in the case of cross domain request, the browser automatically adds an Origin header in the request. There are two cases:

  • Simple requests. This use case applies if we use HTTP GET, HEAD and POST methods. In the case of POST methods, only content types with the following values are supported: text/plain, application/x-www-form-urlencoded and multipart/form-data.
  • Preflighted requests. When the "simple requests" use case doesn't apply, a first request (with the HTTP OPTIONS method) is made to check what can be done in the context of cross-domain requests.

So in fact most of work must be done on the server side to return the CORS headers. The main one is the Access-Control-Allow-Origin one.

200 OK HTTP/1.1 (...) Access-Control-Allow-Origin: * 

To debug such issues, you can use developer tools within browsers (Network tab).

Regarding Angular2, simply use the Http object like any other requests (same domain for example):

return this.http.get('https://angular2.apispark.net/v1/companies/')            .map(res => res.json()).subscribe(   ... ); 
like image 109
Thierry Templier Avatar answered Sep 24 '22 11:09

Thierry Templier