We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

Phalcon Micro REST API CORS header ‘Access-Control-Allow-Origin’ missing

Hello there, I have created REST API using phalcon micro and setup headers as explained in this thread.

Issue is, I'm still getting the below mentioned error in the browser console.

"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api..... (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)."

I noticed that, this error only displays on POST methods and randomly. When i say randomly, i meant i can return response in the biginnig of the function, but when i return response after json_decode or decrypt or after some process, that's the moment i get above error..

My configurations as follows,

asda

$app->before(
function () use ($app) {

    $origin = $app->request->getHeader("ORIGIN") ? $app->request->getHeader("ORIGIN") : '*';

    $app->response->setHeader("Access-Control-Allow-Origin", $origin)
        ->setHeader("Access-Control-Allow-Methods", 'GET,PUT,POST,DELETE,OPTIONS')
        ->setHeader("Access-Control-Allow-Headers", 'Origin, X-Requested-With, Content-Range, Content-Disposition, Content-Type, Authorization')
        ->setHeader("Access-Control-Allow-Credentials", true);

    return true;
});

$app->options('/{catch:(.*)}', function() use ($app) { $app->response->setStatusCode(200, "OK")->send(); });



77.6k
Accepted
answer

try $app->response->sendHeaders() before the return

Tried that too...

try $app->response->sendHeaders() before the return

What is your environment? OS, web server, php and phalcon version?

Also try inspecting the request+response headers in chrome, it may reveal some wonky misconfig

Dear @lajos, It was my bad actually. Your solution worked for me.. Thank you

    $origin = $app->request->getHeader("ORIGIN") ? $app->request->getHeader("ORIGIN") : '*';
    $app->response->setHeader("Access-Control-Allow-Origin", $origin)
        ->setHeader("Access-Control-Allow-Methods", 'GET,PUT,POST,DELETE,OPTIONS')
        ->setHeader("Access-Control-Allow-Headers", 'Origin, X-Requested-With, Content-Range, Content-Disposition, Content-Type, Authorization')
        ->setHeader("Access-Control-Allow-Credentials", true);

 **   $app->response->sendHeaders();**

What is your environment? OS, web server, php and phalcon version?

Also try inspecting the request+response headers in chrome, it may reveal some wonky misconfig