How to create cross-domain request?
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
andmultipart/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(
...
);
For me it was another problem. This might be trivial for some, but it took me a while to figure out. So this answer might be helpfull to some.
I had my API_BASE_URL
set to localhost:58577
. The coin dropped after reading the error message for the millionth time. The problem is in the part where it says that it only supports HTTP
and some other protocols. I had to change the API_BASE_URL
so that it includes the protocol. So changing API_BASE_URL
to http://localhost:58577
it worked perfectly.