laravel 跨域cors中间件封装
<?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, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN'
];
//为空表示允许所有IP和域名访问
$allow_origin = config('cors') ?? [];//格式:'http://127.0.0.1:8080',//允许访问
$origin = $request->server('HTTP_ORIGIN') ?? $_SERVER['HTTP_ORIGIN'] ?? $request->header('Origin') ?? '';
if(!empty($allow_origin) && !in_array($origin,$allow_origin))
{
return response()->json('Forbidden 403 ,Please add to allow access whitelist', 403, $headers);
}
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;
}
}
有需要的可以参考文章来源地址https://www.toymoban.com/news/detail-814620.html
文章来源:https://www.toymoban.com/news/detail-814620.html
到了这里,关于laravel 中间件跨域自定义封装的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!