<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Response;

class CrossHttp
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->isMethod('OPTIONS')) {
            $response = $next($request);
            $response->header('Access-Control-Allow-Origin', '*'); //允许所有资源跨域
            $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, Accept, Authorization, application/json , X-Auth-Token');//允许通过的响应报头
            $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS, DELETE');//允许的请求方法
            $response->header('Access-Control-Expose-Headers', 'Authorization');//允许axios获取响应头中的Authorization
            $response->header('Access-Control-Allow-Credentials', 'true');//运行客户端携带证书式访问
            $response->setStatusCode('200');
        }else{
            $response = $next($request);
            $response->header('Access-Control-Allow-Origin', '*'); //允许所有资源跨域
            $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, Accept, Authorization, application/json , X-Auth-Token');//允许通过的响应报头
            $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS, DELETE');//允许的请求方法
            $response->header('Access-Control-Expose-Headers', 'Authorization');//允许axios获取响应头中的Authorization
            $response->header('Access-Control-Allow-Credentials', 'true');//运行客户端携带证书式访问
        }

        return $response;
    }
}
