简体   繁体   中英

OPTIONS request is not firing with http call through Angular2 Http

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: 在此处输入图片说明

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,

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:

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM