2

Every time I make a put or a post I see 2 calls:

  1. Request Method:OPTIONS | Status Code:200
  2. Request Method:POST | Status Code:201

For a GET I only see one call:

  1. Request Method:GET | Status Code:200

My implementation of the PUT or POST

constructor(
 private http: HttpClient   
) {}    

postShortForm(shortForm: any) {
const req = new HttpRequest('POST', this.preCheckUrl, shortForm, {
  reportProgress: true,
});
return this.http.request(req)
  .retry(3)
}

GET

constructor(
 private http: HttpClient    
) {}    

getApplication(id: any){
interface ItemsResponse {
  results: string[];
}
return this.http
  .get<ItemsResponse>(this.applicationSubmitUrl+this.id.id, {observe: 'response'})
}

Is angular doing something under the hood to make an options request or is something in my code triggering it?

Anthony
  • 2,330
  • 8
  • 44
  • 64
  • 1
    Please see this post : [OPTIONS requests](https://www.google.fr/search?q=options+request&oq=OPTIONS&aqs=chrome.1.69i57j69i59j69i61l2j69i60j0.1303j0j7&sourceid=chrome&ie=UTF-8) –  Sep 06 '17 at 14:15
  • 2
    Possible duplicate of [Why am I getting an OPTIONS request instead of a GET request?](https://stackoverflow.com/questions/1256593/why-am-i-getting-an-options-request-instead-of-a-get-request) (TL;DR: They're CORS preflight requests sent by the browser.) – Joe Clay Sep 06 '17 at 14:22

2 Answers2

4

I think its because of CORS, like request was made at Site A (localhost:4200 or 192.168.1.1:9002) to Site B (192.168.1.1:9000)

The first request is the pre-flight check, to see if the client is allowed to make a request (like for example in the php code in the server its got something like this, denoting that CORS types of requests are allowed)

<?php
  header("Access-Control-Allow-Origin: *");
  header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
  header('Access-Control-Allow-Methods: GET,PUT,POST,DELETE,OPTIONS');
  ....
?>

the first request is type OPTIONS, the second request is the actual request, type GET or POST.

enter image description here

enter image description here

Zarepheth
  • 2,465
  • 2
  • 32
  • 49
2

As per the HttpClient document the post method used code observable and will make 2 calls. Below is the note from HttpClient documentation

Note the subscribe() method. All Observables returned from HttpClient are cold, which is to say that they are blueprints for making requests. Nothing will happen until you call subscribe(), and every such call will make a separate request. For example, this code sends a POST request with the same data twice:

see the details angular HttpClient

Aniruddha Das
  • 20,520
  • 23
  • 96
  • 132