suncoastkid suncoastkid - 1 month ago 28
PHP Question

Laravel 5.2 CORS, GET not working with preflight OPTIONS

The dreaded CORS Error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://localhost/mysite/api/test. (Reason: CORS
header 'Access-Control-Allow-Origin' missing).

Laravel route:

$router->group(['prefix' => 'api', 'middleware' => 'cors'], function ($router) {
$router->get('/test', 'MyController@myMethod');

Laravel Cors Middlware:

public function handle($request, Closure $next)
header('Access-Control-Allow-Origin: *');

$headers = [
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin, Authorization'
if ($request->getMethod() == "OPTIONS") {
// The client-side application can set only headers allowed in Access-Control-Allow-Headers
return Response::make('OK', 200, $headers);

$response = $next($request);
foreach ($headers as $key => $value)
$response->header($key, $value);
return $response;

Laravel Kernel:

protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'cors' => \App\Http\Middleware\CORS::class

Relevant .htaccess:

RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

Relevant Vue.js:

new Vue({
el: '#app',
data: {
//data here
http: {
headers: {
"Authorization": "Basic " + "apiKeyHere"
methods: {
mymethod: function (e)
function (response)
//do something

If I take out the Authorization header option the request works.

I've also tried but still no joy.
Any help appreciated!


Clearly, not the ideal solution but it WORKS. I've added this to the top of my routes.php file:

header('Access-Control-Allow-Origin: *');
header( 'Access-Control-Allow-Headers: Authorization, Content-Type' );

It would be nice to get this working without a hack... alas.

UPDATE: It turned out to be IIS related. I ended up setting the headers in the web.config file and now CORS works without hacking the routes.php file.

          <add name="Access-Control-Allow-Headers" value="Origin, Authorization, X-Requested-With, Content-Type, Accept" />
          <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS,PUT,DELETE" />

If you want to restrict access, you can add outbound rules:

          <clear />
                <rule name="AddCrossDomainHeader">
                    <match serverVariable="RESPONSE_Access_Control_Allow_Origin" pattern=".*" />
                    <conditions logicalGrouping="MatchAll" trackAllCaptures="true">
                        <add input="{HTTP_ORIGIN}" pattern="(http(s)?://((.+\.)?somesite\.com|(.+\.)?anothersite\.org))" />
                    <action type="Rewrite" value="{C:0}" />