我正在尝试做一个小的API,我可以得到一个没有失败或错误的选项请求。我做了这个中间件:
public function handle($request, Closure $next)
{
if ($request->method() === 'OPTIONS') {
$headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods'=>'POST, GET, OPTIONS, PUT, DELETE'
];
return (new Response(' ', 200))
->withHeaders($headers);
}
else {
return $next($request);
};
}我的web.php。
$router->get('/', function () use ($router) {
return $router->app->version();
});
$router->get('/cors', 'CorsController@index');当我使用postman发送请求时,这是可以的,它会向响应添加报头。但是,任何options请求都将得到200响应,并且不会被重定向或做任何事情。
早些时候,我尝试在我的中间件中做到这一点:
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
}但这总是抛出一个MethodNotAllowedError。
另外,当我创建一个新的请求内容时,我会使用我的请求内容。我的问题是如何在laravel中正确处理CORS的options请求,这样就不会抛出错误,也不会丢失我的请求内容?
发布于 2018-02-14 19:40:29
试试这个:
public function handle($request, Closure $next)
{
if($request->getMethod() == 'OPTIONS'){
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Key, Authorization');
header('Access-Control-Allow-Credentials: true');
exit(0);
}
return $next($request);
}https://stackoverflow.com/questions/48786290
复制相似问题