craftcms / element-api

Create a JSON API/Feed for your elements in Craft.
MIT License
498 stars 57 forks source link

CORS problem on v2.8.2, but not 2.7.0 #156

Closed patrikalienus closed 3 years ago

patrikalienus commented 3 years ago

Description

We're using an endpoint to grab the TOS from a Craft post and displaying it inside a JS app. The endpoint we do this through looks like this:

'endpoints' => [
    'cms-api/<country:>/tos' => function ($country) {
        Craft::$app->getResponse()->getHeaders()
            ->set('Access-Control-Allow-Origin', '*')
            ->set('Access-Control-Allow-Headers', '*,authorization');

        return [
            'elementType' => Entry::class,
            'criteria' => [
                'section' => 'termsOfService',
                'site' => getSite($country)
            ],
            'transformer' => function (Entry $entry) {
                return [
                    'id' => $entry->id,
                    'text' => $entry->text,
                    'content' => $entry->redactorSimple
                ];
            },
        ];
    }
];

This works perfectly fine in Element API 2.7.0, but not 2.8.2 (latest at the time of writing).

Requesting the endpoint directly from within the browser works fine and the Access-Control headers both look correct. It's only when requesting the endpoint from a JS app the the problem occurs. The JS app sends HTTP_ORIGIN which the browser does not AFAIK.

Steps to reproduce

  1. Request an endpoint through a JS app and this error pops up in the console:

Access to XMLHttpRequest at '[ENDPOINT]' from origin '[JS APP URL]' 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.

Additional info

"jalendport/craft-queuemanager": "^1.2",  
"nystudio107/craft-cookies": "^1.1",  
"nystudio107/craft-minify": "^1.2.10",  
"nystudio107/craft-retour": "3.1.61",  
"nystudio107/craft-seomatic": "3.4.10",  
"presseddigital/colorit": "1.1.2.1",  
"putyourlightson/craft-blitz": "3.10.3",  
"spacecatninja/imager-x": "v3.5.2",  
"spicyweb/craft-neo": "2.11.9",
brandonkelly commented 3 years ago

Thanks for pointing that out! Just released 2.8.3 with a fix.