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
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.
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.
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:
To be short, in the case of cross domain request, the browser automatically adds an Origin
header in the request. There are two cases:
text/plain
, application/x-www-form-urlencoded
and multipart/form-data
.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( ... );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With