2
votes

I want to call web service from another domain using angular2 typescript. i am using following code to call api

    var req_dict = { 
               method: RequestMethod.Get,
               url: 'http//127.0.0.1:5000/users/',
               headers: this.head
              }
    var options = new RequestOptions(req_dict);
    var req = new Request(options);
    this.http.request(req).subscribe({});

I hosted my application in http//127.0.0.1:8000. I want to use api from port 5000. when i inspected console , request is going to http://127.0.0.1:8000/http//127.0.0.1:5000/users/ i want to call just http//127.0.0.1:5000/users/. how can call api by absolute url in angular2 ?

1
check your url url: 'http//127.0.0.1:5000/users/' it should be url: 'http://127.0.0.1:5000/users/'Vipin Jain
Even if you use http it should be url: 'http://127.0.0.1:5000/users/'SeRu
oh.. yeah.. thanks. workedopen source guy

1 Answers

4
votes

In fact, it's not an issue of TypeScript or Angular2 but a CORS issue. These blog posts could help you to understand in details how this 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:

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

Hope it helps you, Thierry