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
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(
...
);