Ahmed K
Ahmed K

Reputation: 3

Angular $http executed twice when using headers

I'm developing an ionic project and I'm using header parameters in each POST and GET Request. How ever When I test the project on Android Phone and monitor all requests that come into my server through my android device there are no issues. But when I deploying my ionic project and testing it in my web browser ( Chrome Web Browser ) I see that each request has been executed twice,( one without headers params and without inputs when I use POST method, and the second one is with all params ). I've solved it in my server if there are no header parameters to ignore the request each time. How can I prevent the duplicated execution for the $http (POST and GET)? These parameters I've set in the angular.config js file.

$httpProvider.defaults.headers.common['Accept'] = 'application/json; q=0.01';
$httpProvider.defaults.headers.common['Authorization-Token'] = value;

and my PHP service starts with

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type, Authorization-Token");
header('Access-Control-Max-Age: 60');
header('Access-Control-Allow-Methods: ["GET","POST"]');
header("Content-Type: application/json; charset=UTF-8");

Upvotes: 0

Views: 741

Answers (3)

CommonToast
CommonToast

Reputation: 708

Sounds like an OPTION call indeed.

It should be done, and not carry any payload, it is just to check with the server what actions are allowed on the resource before performing the actual call (post/get/whatever).

Check the answer to this similar question : Angular 2 HTTP POST does an OPTIONS call

Upvotes: 1

Omri Lugasi
Omri Lugasi

Reputation: 327

It all comes down to how browsers manage CORS. When making a cross-domain request in JavaScript that is not "simple" (i.e. a GET request), the browser will automatically make a HTTP OPTIONS request to the specified URL/URI, called a "pre-flight" request or "promise". As long as the remote source returns a HTTP status code of 200 and relevant details about what it will accept in the response headers, then the browser will go ahead with the original JavaScript call

Please look here and here

Upvotes: 0

Zakaria
Zakaria

Reputation: 15070

The first request is the preflight. This is part of the browser mechanism. You cannot avoid it.

Upvotes: 0

Related Questions