Now after starting to learn Angularjs and Laravel 4 I just love the way one can just set up a working development server with just one terminal command without having to set up virtualhosts or anything like that.
However...
I want to develop my frontend seperately so I can utilize the wonderful combination of yeoman and gruntjs and since I really can't do this if I put everything in laravel public folder (or at least I don't know how) this leaves me with the following situation:
I have a frontend grunt server at localhost:9000
And
I have a laravel 4 server at localhost:8000
This will of course mean that in order for Angularjs to talk with Laravel I have to allow CORS. In Apache this is easy: just adding Header add Access-Control-Allow-Origin "localhost:9000"
to the directory part of httpd.conf allows this url to communicate with localhost.
Now where should I put this cors configuration when serving stuff via artisan if its even possible?
Alright found the answer at least one working for me. It would seem I was approaching the problem from the wrong direction since I concentrated on Apache instead of Laravel itself.
In order to allow Cross Origin Response in a development environment via artisan the following code should be inserted in filters.php
:
<?php
...
App::before(function($request)
{
if($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
$statusCode = 204;
$headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers' => 'Origin, Content-Type, Accept, Authorization, X-Requested-With',
'Access-Control-Allow-Credentials' => 'true'
];
return Response::make(null, $statusCode, $headers);
}
});
App::after(function($request, $response)
{
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
$response->headers->set('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization, X-Requested-With');
$response->headers->set('Access-Control-Allow-Credentials', 'true');
return $response;
});
...
Also in case it is relevant I also added 'Access-Control-Allow-Origin' => '*'
to Apache configation.
So now I can run my server environment in localhost:8000 and my frontend in localhost:9000 and they can talk to each other without problem.
I faced the same issue. You can find cors configuration in config/cors.php
. By default all origins allowed only for api/*
routes. You can add your own routes (e.g. oauth
) to it like following:
'path' => ['api/*', 'oauth/*']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With