0

I am playing a bit with Angular2 structure and I got to the point where I want to pull information from the server. Now, my api's domain is different from the FrontEnd app, and I am expecting that the browser will fire OPTIONS request before executing the actual one. However, that is not happening. Instead, what I get is an error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/rrm/api/v1/goals. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

And my network log looks like this: enter image description here

My dead simple Angular2 code is as follows:

export class AppComponent implements OnInit {

  goals: Object[];

  constructor(public authHttp: AuthHttp) {}

  ngOnInit():any {
    this.getGoals();
  }

  getGoals() {
    this.authHttp.get('http://localhost:8080/rrm/api/v1/goals')
        .subscribe(
            data => this.goals = data.arrayBuffer(),
            err => console.log('Error ', err),
            () => console.log('Request Complete')
        );
  }
}

What am i missing? I am not getting options request on the server and I don't see it in the browser...

Thanks,

Shurik Agulyansky
  • 2,607
  • 2
  • 34
  • 76

2 Answers2

4

In fact, there are two main cases in CORS:

  • Simple requests. We are in this case if we use HTTP methods GET, HEAD and POST. In the case of POST method, only content types with following values are supported: text/plain, application/x-www-form-urlencoded, multipart/form-data. Even if you're in these case and if you use a custom header (a header that you define by your own in your request), you'll fall into the preflighted request.

  • Preflighted requests. When you aren't in the case of simple requests, a first request (with HTTP method OPTIONS) is done to check what can be done in the context of cross-domain requests.

In your case, you're in the first case (simple request).

Moreover your GET request should define a Access-Control-Allow-Origin header in its response not to have the error. This will allow the browser to determine if you're (localhost:3000 for example) able to execute the request.

This article could interest you:

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
-1

The OPTIONS is only sent befor every POST request. For GET requests an OPTIONS preflight request is only sent if you have custom headers like auth-headers.

See also Why am I getting an OPTIONS request instead of a GET request?

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567