Lumen: Enable CORS

流过昼夜 提交于 2019-12-04 05:49:24

Add following headers into public/.htaccess file.

Header set Access-Control-Allow-Origin "*" 
Header set  Access-Control-Allow-Methods "GET,POST,PUT,DELETE,OPTIONS"
Header set Access-Control-Allow-Credentials "true"

this is working fine for to resolve Cross Origin Issue.

In Lumen, you need to setup OPTIONS routes manually for every POST, PUT, DELETE... routes.

This is what I did to resolve the problem.

$app->options('{all:.*}', ['middleware' => 'cors.options', function() {
    return response('');
}]);

The route above will catch all the OPTIONS requests for you.

In cors.options middleware:

public function handle($request, Closure $next)
{
    return $next($request)
        ->header('Access-Control-Allow-Origin', $_SERVER['HTTP_ORIGIN'])
        ->header('Access-Control-Allow-Methods', 'PUT, POST, DELETE')
        ->header('Access-Control-Allow-Headers', 'Accept, Content-Type,X-CSRF-TOKEN')
        ->header('Access-Control-Allow-Credentials', 'true');
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!