laravel 中间件跨域自定义封装

发布时间:2024年01月22日

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://blog.csdn.net/t_fengyun/article/details/135743318
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。