This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.
I've read a couple how-to's on enabling CORS for Laravel 5.1 and am wondering how I can achieve this in octobercms too.
I'm developing a REST-API on top of octobercms and only need CORS for the API endpoint. The REST-API ist residing in a plugin so basically my plugin needs to enable CORS.
Thanks in advice for any help.
Last updated
I've got it working today using a before filter and an Route::options('{all}')
.
Both call the same controller method:
use Illuminate\Routing\Controller;
use Request;
use Response;
use Config;
class Cors extends Controller {
public function handle() {
$validDomain = Config::get('app.cors.allow_origin');
$domain = Request::server('HTTP_HOST');
if ($validDomain != '*' && $validDomain != $domain) {
return Response::make('Access denied', 403);
}
// Enable CORS
header('Access-Control-Allow-Origin: ' . $validDomain);
header('Access-Control-Allow-Credentials: true');
if (Request::getMethod() == "OPTIONS") {
// The client-side application can set only headers allowed in Access-Control-Allow-Headers
$headers = [
'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers'=> 'X-Requested-With, Content-Type, X-Auth-Token, Origin, Authorization'
];
return Response::make('You are connected to the API', 200, $headers);
}
}
}
If you want to do it nicely, you can register a middleware to do it. An example can be found here: https://github.com/barryvdh/laravel-cors (It also uses a middleware).
Middleware docs: http://laravel.com/docs/5.0/middleware
To regsister the middleware for octobers (frontend) routes, you can use the init.php: https://github.com/alxy/oc-captcha-plugin/blob/master/init.php#L6-L8
I was searching on how to add middlewares in octoberCMS but without any luck. Thank you for the hint.
Hi Ondrej In which file did you place the Route::options('{all}') ? I'm trying to get this to work, but no success so far...
Thank you
gregorybleiker8797 said:
Hi Ondrej In which file did you place the Route::options('{all}') ? I'm trying to get this to work, but no success so far...
Thank you
within the root of my plugin in routes.php
I've found out that Apache does not always forward CORS requests to PHP. This was the case in my production environment. And the HTTP_HOST is not always set driving PHP-side CORS useless. I switched to enable CORS in .htaccess instead.
Thank you for that! I spent my evening trying to get my new Valet ngnix dev setup to allow CORS and couldn't get anything to work until I tried your plugin.
1-9 of 9