HTTP GET request changes to OPTIONS when adding headers in angular js
Below is the query I have used so far
$http.get(url)
.success(function (data){})
.error(function (data){})
works without any problem with CORS. My server side Allows all sources, methods, all headers
when i add http header like
$http.get(url, { headers: { "USERID": user, "SESSIONID": sessionId}})
the request changes to OPTIONS method when I see in the Network tab of Chrome Tools
What is the reason for this? if expected how to add custom http headers.
I went through this link angularjs-performs-an-options-http-request-for-a-cross-origin-resource but it didn't help
Here I am expecting the server to resolve different origins . But this only allows headers if I was on the same server. But not sure about this - on angular or server side.
after the headlines
$ http.get (url, {headers: {"USERID": user, "SESSIONID": sessionId}})
in hrome dev tools i see how
Request Method:OPTIONS
Status Code:404 Not Found
but no headers
Request Method:GET
Status Code:200 OK
When I do this in the REST Client, I can send the headers to the server.
source to share
$http({method: 'GET', url: '/someUrl', headers: { "USERID": user, "SESSIONID": sessionId}}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
will work. $ http.get is a quick access method. Check config
in docs
source to share
This is a known bug, see for example https://github.com/angular/angular.js/issues/1585 .
The workaround is to use jQuery query.
source to share
I had the same massive problem when trying to pass a title in my get where it changed to go to parameters and didn't work. To do this, I added the following to the php api
<?php if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']) && $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] == 'GET') {
header("Access-Control-Allow-Headers: Authorization, X-Auth-Token");
}
exit;
} ?>
You can allow any headers you want to transfer. Hope it helps
source to share
For my specific problem with my C # Web API solution, I needed to handle something with an option request. Angular was posting a pre-flight options request method which I allowed in my web.config with
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS, PATCH" />
But that was not enough, I also included a method to handle the parameter request and I didn't answer anything
[ResponseType( typeof( void ) )]
public IHttpActionResult OptionsPost() {
return StatusCode( HttpStatusCode.NoContent );
}
source to share