thinkphp跨域很齐全的处理方式


declare (strict_types=1);

namespace app\middleware;

class admin
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        /** @var Response $response */
        $response = $next($request);
        $response->header([
            'Access-Control-Allow-Origin' => 'http://localhost:8080', // 允许跨域域名
            'Access-Control-Expose-Headers' => 'Authorization', // 允许跨域前端读取的headers
            'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE',// 允许的mehtods
            'Access-Control-Allow-Headers' => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With,authorization', // 允许传至后端的headers
            'Access-Control-Allow-Credentials' => 'true' // 允许跨域cookie传输
        ]);
        if (strtoupper($request->method()) == "OPTIONS") {
            return $response;
        }
        return $response;
    }
}

相关注释已在其中写明!

你可能感兴趣的:(Thinkphp,ThinkPHP6.0,thinkphp5.0)