Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$http headers gets added under Access-Control-Request-Headers

Whenever I try to add custom Request headers to my $http request the headers does not show up in the Request, instead its comes under Access-Control-Request-Headers like Access-Control-Request-Headers:accept, testHeader See below the output in chrome's network tab:

Request Headers: 
    OPTIONS /v/xyx/abc/query?q=SELECT%20duration%20FROM%20TimeTable HTTP/1.1
    Host: example.com
    Connection: keep-alive
    Access-Control-Request-Method: GET
    Origin: http://localhost
    User-Agent: XXXXXXXX Chrome XXXXXXX
    Access-Control-Request-Headers: accept, testHeader
    Accept: */*
    Referer: http://localhost/test/
    Accept-Encoding: gzip, deflate, sdch
    Accept-Language: en-US,en;q=0.8

Whereas,I am expecting something like:

Request Headers: 
    OPTIONS /v/xyx/abc/query?q=SELECT%20duration%20FROM%20TimeTable HTTP/1.1
    Host: example.com
    Connection: keep-alive
    Access-Control-Request-Method: GET
    Origin: http://localhost
    User-Agent: XXXXXXXX Chrome XXXXXXX
    Accept: application/json
    testHeader: zdhfguwe87fg8378287efijb8
    Referer: http://localhost/test/
    Accept-Encoding: gzip, deflate, sdch
    Accept-Language: en-US,en;q=0.8

How can I prevent this from happening and show the headers under Request header?

See the config of the $http service in Angularjs that I've followed:

//***TRIED BOTH OF THESE: 
//***TRY#1 $http.get(url, {headers:{"Accept": "application/json", "testHeader": "zdhfguwe87fg8378287efijb8"}}).then(.......
//***TRY#2
      $http({
        method: 'GET',
        url: url,
        headers: {
          "Accept": "application/json",
          "testHeader": "zdhfguwe87fg8378287efijb8"
        }
      })
      .then(
        function(){
          //success
          console.log(arguments);
        }, function(){
          //fail
          console.log(arguments);
        });
like image 991
Temp O'rary Avatar asked Dec 15 '22 10:12

Temp O'rary


1 Answers

This is expected behavior as part of the CORS-preflight, which is an OPTIONS request. Once this request succeeds, the actual GET request will be fired by the browser with the custom headers, because the server accepted them.

Only a limited set of headers is approved by default for CORS requests, therefore to add others (including your custom header), the CORS-preflight request needs to ask the server for permission with the Access-Control-Request-Headers HTTP header.

See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests

like image 169
Bart Verkoeijen Avatar answered Feb 16 '23 00:02

Bart Verkoeijen