snelg / cakephp-cors

CORS plugin for CakePHP 3
19 stars 2 forks source link

Add CORS headers when throwing Exceptions #11

Closed avinashjoshi closed 8 years ago

avinashjoshi commented 8 years ago

I get the following error when throwing exceptions like 404 or 401 or 422 etc

XMLHttpRequest cannot load http://api.domain.dev/v1/auth/token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://domain.dev:9000' is therefore not allowed access. The response had HTTP status code 400.

Works perfectly on 200. Is there a way fix this?

snelg commented 8 years ago

Sorry for the very slow reply. The way this tiny plugin works is through the DispatcherFactory functionality in CakePHP 3. Exception handling breaks out from that completely and does its own response rendering.

So you need to set the "Access-Control-Allow-[xxx]" headers when you create the exception yourself, e.g.

    $e = new NotFoundException();
    $e->responseHeader(['Access-Control-Allow-Origin' => '*']);
    throw $e;

instead of just

    throw new NotFoundException();

Or you can write your own exception handler http://book.cakephp.org/3.0/en/development/errors.html