1

I send a POST request from a headless frontend to a craft controller action but the request is not going trough because of:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localcraft.ddev.site/add-comment. (Reason: CORS request did not succeed). Status code: (null).

(I set a custom route in routes.php, so I can reach the action via /add-comment).

I think I have to do something with $response = Craft::$app->getResponse(); But I can't figure out what.

I also set this at the beginning of my controller:

class AddToQueueController extends Controller
{
    protected array|bool|int $allowAnonymous = ["add-comment"];
    public $enableCsrfValidation = !["add-comment"];

But that does not help either...

I am glad for any help! Cheers

1 Answer 1

2

Ok I realized that this works:

$response = Craft::$app->getResponse();
$response->headers->set("Access-Control-Allow-Origin", "*");

But somehow my axios POST request still has CORS preflight issue, although I can see the headers set in Insomnia...

I have to look for the actual problem now.

===================== Edit: Well together with Chat GPT I found out that I kind of need to return the response early for an OPTIONS request. So the CORS preflight gets the headers.

$response = Craft::$app->getResponse();

$response->headers->set("Access-Control-Allow-Origin", "*");
$response->headers->set(
    "Access-Control-Allow-Methods",
    "GET, POST, OPTIONS"
);
$response->headers->set("Access-Control-Allow-Headers", "Content-Type");
$response->headers->set("Content-Type", "application/json");

if (Craft::$app->getRequest()->getMethod() === "OPTIONS") {
    // for CORS preflight we need to return the request early.
    return $response;
}

I don't fully understand, why I need to do that specifically, but somehow these headers are missing if I don't. I also can't really imagine that this is not a more commonly met problem... and not documented here already...

Anyway, I hope this helps somebody one day. Cheers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.