Skip to content
This repository has been archived by the owner on Feb 20, 2025. It is now read-only.

Commit

Permalink
Added CORS policy and added an OPTIONS fallback
Browse files Browse the repository at this point in the history
  • Loading branch information
teilin committed Apr 11, 2021
1 parent 5749e2d commit 47535e4
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 1 deletion.
39 changes: 39 additions & 0 deletions app/Http/Middleware/CorsMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php
namespace App\Http\Middleware;

use Closure;

class CorsMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Max-Age' => '86400',
'Access-Control-Allow-Headers' => 'Origin, Content-Type, X-Auth-Token, Authorization, Accept, X-Varnish, Via, Age, Accept-Ranges, Connection, Content-Length, Content-Encoding, Vary, Cache-Control, X-Powered-By, Server, Date'//'Content-Type, Authorization, X-Requested-With'
];

if ($request->isMethod('OPTIONS'))
{
return response()->json('{"method":"OPTIONS"}', 200, $headers);
}

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

return $response;
}
}
?>
1 change: 1 addition & 0 deletions bootstrap/app.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@

$app->routeMiddleware([
'auth' => App\Http\Middleware\AuthMiddleware::class,
'cors' => App\Http\Middleware\CorsMiddleware::class,
]);

/*
Expand Down
6 changes: 5 additions & 1 deletion routes/web.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
return $router->app->version();
});

$router->group(['prefix'=>'api/v1', 'middleware' => 'auth'], function() use($router){
$router->group(['prefix'=>'api/v1', 'middleware' => ['cors', 'auth']], function() use($router){
// Festival
$router->get('/festival', 'FestivalController@index');
$router->post('/festival', 'FestivalController@create');
Expand Down Expand Up @@ -69,4 +69,8 @@
$router->get('/inventory/{inventory_id}/count', 'InventoryCountController@countsByInventory');
$router->post('/inventory/{inventory_id}/count', 'InventoryCountController@create');
$router->delete('/count/{id}', 'InventoryCountController@destroy');
// Fallback
$router->options('{any:.*}', function (){
return;
});
});

0 comments on commit 47535e4

Please sign in to comment.