laravel 跨域问题

今天在看laravel5.6  本地开发,当其他人ip访问出现错误  一系列header连接出错   

然后找了一下原因

 public function handle($request, Closure $next)
    {

        header("Access-Control-Allow-Origin: *");

        // ALLOW OPTIONS METHOD
        $headers = [
            'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers'=> 'Content-Type, Origin, Cookie ,  X-Requested-With'
        ];
//        if($request->getMethod() == "OPTIONS") {
//            // The client-side application can set only headers allowed in Access-Control-Allow-Headers
//            return Response::make('OK', 200, $headers);
//        }


        $response = $next($request);
        foreach($headers as $key => $value)
            $response->header($key, $value);
        return $response;
    }
Access-Control-Allow-Headers     里面参数可以自行根据所需要条件添加

Access-Control-Allow-Origin      一样可以根据业务需求开放相应域名

添加到中间件,完成中间件注册  即可使用

参考  http://www.jb51.net/article/117561.htm

        https://stackoverflow.com/questions/33076705/laravel-5-1-api-enable-cors

猜你喜欢

转载自blog.csdn.net/weixin_40076986/article/details/79564020