jquerycorsphilips-hue

Philips Hue API V2 - CORS Error "No 'Access-Control-Allow-Origin' header"


I have an HTML page that includes JavaScript and jQuery code to control my Philips Hue hub. Using their v1 API everything works, but this API is being deprecated so I am moving to v2.

I am trying to do a simple jQuery ajax call to the hub to retrieve the list of lights. The request works perfectly in Postman (of course!), but when I try it in Chrome of Firefox (using jQuery ajax calls) I get CORS errors.

My stripped down JavaScript function:

    function test() {
        $.ajax({
            url: 'https://10.0.0.22/clip/v2/resource/light', 
            type: 'GET',
            headers: {'hue-application-key': 'lqm3XXXX_REDACTED_XXXXzh4YDp'},
            success: function (data) {
                x = JSON.stringify(data, null, '\t');
                $("#response").html(x);
            },
        });
    }

In Firefox 108 and in Chrome 108 I get this error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://10.0.0.22/clip/v2/resource/light. (Reason: CORS preflight response did not succeed). Status code: 403.

The above is when I host the HTML file on a local web server. If I try to access the hub from a hosted server on the internet, I get the following:
Access to XMLHttpRequest at 'https://10.0.0.22/clip/v2/resource/light' from origin 'https://www.mywebserver.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

It seems to me that the Hue bridge is (or should be) set up to "Access-Control-Allow-Origin: *" otherwise 3rd party apps would never work with it.

I've google the heck out of this and it seems like I'm one of the very few having this specific issue, which makes me think I am doing something wrong.

Could this be a bug in my hub? A bug in my code? Am I simply SOL because what I am trying to do is not possible and I should write a native app instead of using JavaScript in a browser?


Solution

  • This is a long-standing issue with the v2 API.

    The v1 API returned CORS headers with all HTTP responses, but the v2 API responses are missing the CORS headers.

    These are the forum posts I've been able to find relating to this issue, but there has not been any response from Philips:

    Until Philips sorts this out and updates the v2 API to return CORS headers you will have to make your API requests via a proxy server that can add the headers for you.