美文网首页
laravel 跨域

laravel 跨域

作者: 9a4a58bf4d80 | 来源:发表于2019-10-30 11:23 被阅读0次
  1. 创建中间件
    先检查 app/Http/Middleware/ 下是否有 EnableCrossRequestMiddleware.php 这个文件,没有此文件使用此命令创建
php artisan make:middleware EnableCrossRequestMiddleware

2.修改内容
然后修改 EnableCrossRequestMiddleware.php 的 handle

 public function handle($request, Closure $next)
    {
        $response = $next($request);
        $origin = $request->server('HTTP_ORIGIN') ? $request->server('HTTP_ORIGIN') : '';
        //允许访问
        $allow_origin = [
//            'http://jijiu.com',
        "*"
        ];

        if (app()->environment() == 'local') {
            $response->header('Access-Control-Allow-Origin', "*");
        } else if (in_array($origin, $allow_origin)) {
            $response->header('Access-Control-Allow-Origin', $origin);
        }
        $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN');
        $response->header('Access-Control-Expose-Headers', 'Authorization, authenticated');
        $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE, OPTIONS');
        $response->header('Access-Control-Allow-Credentials', 'true');
        $response->header('Access-Control-Max-Age', 86400); // 时间为24小时 单位:秒
        return $response;
    }

3.注册中间件
然后找到 app/Http/Kernel.php 文件中的 protected $middleware

protected $middleware = [
    \App\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    \App\Http\Middleware\TrustProxies::class,
    \App\Http\Middleware\EnableCrossRequestMiddleware::class,//新增跨域中间件
];

相关文章

网友评论

      本文标题:laravel 跨域

      本文链接:https://www.haomeiwen.com/subject/ullovctx.html