laravel实现跨域的中间件

# 创建中间件
php artisan make:middleware EnableCrossRequestMiddleware
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class EnableCrossRequestMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $origin = $request->header('Origin');
        if ($origin) {
            $exps = [
                '/.*\.xxx\.com$/', # 匹配下自己的域名
                '/.*localhost.*/',
                '/.*127.0.0.1.*/',
                '/.*10.*/',
            ];
            foreach ($exps as $exp) {
                $matchCount = preg_match($exp, $origin, $matches);
                if ($matchCount && isset($matches[0])) {
                    if ($request->isMethod('OPTIONS')) {
                        $response = response('');
                        $response->withHeaders([
                            'Access-Control-Allow-Credentials' => 'true',
                            'Access-Control-Allow-Origin' => $origin,
                            'Access-Control-Allow-Methods' => 'GET, POST',
                            'Access-Control-Allow-Headers' => 'Content-Type, Token',
                            'Access-Control-Max-Age' => 3600 * 24,
                        ]);
                        return $response;
                    }
                    $response = $next($request);
                    $response->withHeaders([
                        'Access-Control-Allow-Credentials' => 'true',
                        'Access-Control-Allow-Origin' => $origin,
                    ]);
                    return $response;
                }
            }
        }
        return $next($request);
    }
}

另外需要关闭csrf保护否则会413

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注