I recently tries enabling CORS in Laravel 5.4 but unfortunately it doesn\'t want to work. I have included the code and the error that it\'s giving me below. Can anyone help
Just add this code on your routes
header('Access-Control-Allow-Origin: http://yourdomain.com/');
See https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS#Preflighted_requests_in_CORS
If your problem in OPTIONS method.
Kernel::$routeMiddleware not working in Laravel 5.4 for request method OPTIONS, see https://github.com/laravel/framework/blob/v5.4.0/src/Illuminate/Routing/RouteCollection.php#L214. For use CORS middleware, enable it in Kernel::$middleware array. It is not good, but no other way.
For example, I use next middleware class for SPA and API, attention, it is not middleware 'cors' for routes
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
/**
* OptionsCorsResponse middleware - add CORS headers if request method OPTIONS
*/
class OptionsCorsResponse
{
/**
*
* @param Request $request
* @param Closure $next
* @return Response
*/
public function handle($request, Closure $next)
{
/* @var $response Response */
$response = $next($request);
if (!$request->isMethod('OPTIONS')) {
return $response;
}
$allow = $response->headers->get('Allow'); // true list of allowed methods
if (!$allow) {
return $response;
}
$headers = [
'Access-Control-Allow-Methods' => $allow,
'Access-Control-Max-Age' => 3600,
'Access-Control-Allow-Headers' => 'X-Requested-With, Origin, X-Csrftoken, Content-Type, Accept',
];
return $response->withHeaders($headers);
}
}
and enable it in App\Http\Kernel
protected $middleware = [
// ...
\App\Http\Middleware\OptionsCorsResponse::class,
];
Origin 'http :// ice . domain . uk' is therefore not allowed access. The response had HTTP status code 500.
Debug your code, because it generate some exception. Use any REST client with OPTIONS method.