putyourlightson / craft-sprig

A reactive Twig component framework for Craft CMS.
https://putyourlightson.com/plugins/sprig
MIT License
124 stars 9 forks source link

No 'Access-Control-Allow-Origin' header is present on the requested resource #362

Closed svondervoort closed 5 months ago

svondervoort commented 5 months ago

Support Request

Somehow Sprig is still failing with CORS error No 'Access-Control-Allow-Origin' header is present on the requested resource. I saw somewhere you stated Sprig uses the site's base URL, but in this case in a multisite it seems to always be using the base URL of the default site instead of the currentSite. Am I missing something here?

Plugin Version

2.8.0

bencroker commented 5 months ago

Action URLs, which is what Sprig uses, are always routed to the base URL. So you may need to add a CORS header to allow subdomains to access the naked domain name.

svondervoort commented 5 months ago

We just added the CORS header to allow certain domains, now the next error pops up:

Access to XMLHttpRequest at 'https://www.wesselman-info.nl/index.php?p=actions/sprig-core/components/render...' from origin 'https://www.werkenbijwesselman.nl' has been blocked by CORS policy: Request header field hx-target is not allowed by Access-Control-Allow-Headers in preflight response.

Do you know a list of all the HTMX headers we need to allow to make this work?

bencroker commented 5 months ago

They are documented at https://htmx.org/docs/#cors, but I’d suggest allowing all headers from trusted domains. So for example:

Access-Control-Allow-Origin: https://www.werkenbijwesselman.nl
Access-Control-Allow-Headers: *
svondervoort commented 5 months ago

Thanks, we will give it a go.

bencroker commented 5 months ago

I looked into this further and it may have to do with how you’re setting the @web alias.

According to https://github.com/craftcms/cms/issues/14676#issuecomment-2019221993, you should not be using @web in your base site URLs(s) nor setting @web explicitly.

If you stick with avoiding @web and explicitly setting your base site URLs, Craft will define @web automatically based on the actual requested URL to index.php, and all will be fine.

svondervoort commented 5 months ago

Thanks for taking another look into this. The weird thing is we need to set the @web for a Blitz feature to work https://github.com/putyourlightson/craft-blitz/issues/612. So I'm not sure what to do right now.

bencroker commented 5 months ago

You don’t need to define @web, and in this case you shouldn’t. Instead, replace @web in all base site URLs and filesystem URLs with absolute URLs or with unique environment variables, and things should work as expected.

See the warning at https://craftcms.com/docs/5.x/system/sites.html#step-1-create-the-site

screenshot-eFAnSETr@2x