20

The error is the following:

XMLHttpRequest cannot load http://some_url.herokuapp.com/api/some_api/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 503.

when calling

return this._http.post(requestUrl, JSON.stringify(requestBody), requestOptions)

I had troubles with CORS (when working with Angular 1) in the past and I remember that once CORS were activated server-side,I had to transform the http request to parse certain HTTP headers.

I am quite confused about how it should work, so any explanation is very welcome.

David Buck
  • 3,752
  • 35
  • 31
  • 35
dragonmnl
  • 14,578
  • 33
  • 84
  • 129
  • This might be a server-side problem. API is responding with 503, so maybe it's some kind of error handler (e.g. in proxy service) that doesn't provide "Access-Control-Allow-Origin" headers like the rest of your backend? – jkondratowicz Apr 21 '16 at 11:42
  • turns out it's actually a backend issue. – dragonmnl Apr 21 '16 at 12:12

2 Answers2

19

In fact, it's not an Angular2 issue but a problem at the server side. The preflighted OPTIONS request needs to return an Access-Control-Allow-Origin header in its response.

Sending the Origin header in the original request will enable the CORS support on the server side. This header is automatically added by the browser when it detects that the domain of the request isn't the same as the caller's.

Be careful when implementing the preflight OPTIONS request on the server side since credentials aren't sent at this level. They are only sent within the target request. It seems to be the problem since you have 503 error. You're trying to check if the OPTIONS request is authenticated but it's not actually the case...

See this article for more details:

Neoheurist
  • 3,183
  • 6
  • 37
  • 55
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
0
login(loginDetails:LoginDetails){

    const headers = new HttpHeaders({ Authorization: 'Basic ' + btoa(loginDetails.getUserName + ':' + loginDetails.getPassword) });

    this.http.post(this.url,loginDetails,{headers,responseType:'text' as 'json'}).subscribe(
        (result)=>{
            console.log(result)
            this.router.navigate(['/home']);
        },
        err=>{
            this.router.navigate(['/registration']);
        }
    )
}
Taazar
  • 1,545
  • 18
  • 27
Bhushan
  • 104
  • 1
  • 9