0

So, I am doing this request:

$http({
    method: 'GET',
    url: query,
    headers: { 'api-key': 'test-api-key' }
});

In Chrome Developer Tools Network tab I can see the request being sent:

Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,sv;q=0.6
Access-Control-Request-Headers:accept, api-key
Access-Control-Request-Method:GET
Cache-Control:no-cache
Connection:keep-alive
Host:my-host.myhost.net
Origin:http://localhost:24153
Pragma:no-cache
Referer:http://localhost:24153/
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36
X-FirePHP-Version:0.0.6

Q: What possible reasons may there be that the header is not added to the request?

Marcus
  • 8,230
  • 11
  • 61
  • 88

1 Answers1

2

You are making a cross-origin Ajax request with custom headers.

That makes it a complex request so the browser has to send a pre-flight OPTIONS request to get permission to make the cross-origin Ajax request.

If and when the server responds correctly to the OPTIONS request, the browser will make the GET request with the additional header you want.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Ok, got you, so enabling CORS, setting `Access-Control-Allow-Origin` to `*` on the server side should enable the server to respond to the OPTIONS request and the custom header should be added? But any ideas to why this request works using Postman? – Marcus Dec 17 '15 at 09:39
  • 1
    Chrome packaged apps can have cross domain permissions. See [this post](http://stackoverflow.com/questions/16021442/how-postman-send-requests-ajax-same-origin-policy) for more information. – Luuk Moret Dec 17 '15 at 09:41
  • Unfortunately, adding the `Access-Control-Allow-Origin` response header and setting it to `*` did not help. – Marcus Dec 17 '15 at 09:52
  • @Marcus — No, you need to respond with a `200 OK` that includes suitable `Access-Control-Allow-Origin`, and `Access-Control-Allow-Headers` (and probably `Access-Control-Allow-Methods`) headers. You're adding custom headers, allowing the origin alone is insufficient. There's an example in the MDN documentation linked to above. – Quentin Dec 17 '15 at 10:03
  • Added `Access-Control-Allow-Headers: Content-Type Access-Control-Allow-Methods: GET, POST, OPTIONS Access-Control-Allow-Origin: *` to server response headers, issue remains. – Marcus Dec 17 '15 at 10:07
  • 1
    Err. How about saying that the `api-key` header that you are adding is allowed?! – Quentin Dec 17 '15 at 10:08
  • Tried: `Access-Control-Allow-Headers:X-Requested-With, content-type, api-key` and `Access-Control-Allow-Headers:*` but issue remains. Maybe the CORS package will help... – Marcus Dec 17 '15 at 10:20