0

So I have the following code snippet for carrying out a get request authenticated with a token to an API:

<script>
$.ajax({
    url: "<API URL>",
    type: 'GET',
    headers: {"X-Api-Key": "<API Key>"}
});
</script>

The issue is that the API doesn't seem to actually receive the API key data. I get back a MissingAuthenticationTokenException.

Moreover, when I look at the raw request data in the browser I see:

Access-Control-Request-Method: GET
Access-Control-Request-Headers: x-api-key

You'll notice it lists x-api-key but doesn't seem to show any value assigned to it.

In contrast, on the command line I make successful GET calls with the following command:

curl -X GET -H 'X-Api-Key: <API KEY>' '<API URL>'

How can I alter my script to correctly pass the header data to the API?

GenTel
  • 1,448
  • 3
  • 13
  • 19
  • If you `console.log()` the `API key` value within the scope of the `ajax` call, is the expected value output to the console? We may need to see more code. – Fred Gandt Jun 24 '17 at 00:22
  • Alright, how can I console.log in this context? The relevant data is in an anonymous map where we can't put functions. – GenTel Jun 24 '17 at 00:30
  • If this is a cross domain request then issue is CORS related. No custom headers get sent with OPTIONs preflight request. Probably need to set up a proxy. See https://stackoverflow.com/questions/30920422/how-to-handle-custom-headers-with-cors-pre-flight-request-ajax-codeigniter and https://stackoverflow.com/questions/13994507/how-do-you-send-a-custom-header-in-a-cross-domain-cors-xmlhttprequest – charlietfl Jun 24 '17 at 00:31
  • If `ajax` hasn't got access to the value, it can't send it in the header, so, try console.logging the value within the same scope as the `ajax` call to see if that's the problem. – Fred Gandt Jun 24 '17 at 00:32
  • Oh, it's a string literal so I guarantee it's got access. – GenTel Jun 24 '17 at 00:34
  • Have you tried using [`beforeSend`](http://api.jquery.com/jquery.ajax/) instead of `headers`? Does that work? – Fred Gandt Jun 24 '17 at 01:11

0 Answers0