Laravel Cors (Middleware NOT working)

后端 未结 8 1582
孤独总比滥情好
孤独总比滥情好 2020-12-31 12:37

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

8条回答
  •  余生分开走
    2020-12-31 13:18

    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

    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.

提交回复
热议问题