美文网首页我爱编程
对于 Laravel 路由请求跨域问题的解决方案

对于 Laravel 路由请求跨域问题的解决方案

作者: Martain | 来源:发表于2018-04-09 11:03 被阅读165次

    对于Laravel 路由请求跨域问题的解决方案 (未整理,很乱版,太懒了)

    一、创建添加 响应头 的中间件,并将中间件分配给每个路由

    php artisan make:Middleware OpenRequest
    
    //修改OpenRequest 的handle方法
     public function handle($request, Closure $next)
        {
            $response = $next($request);
            $response->header('Access-Control-Allow-Origin', '*');
            $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, Accept');
            $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS');
    //        $response->header('Access-Control-Allow-Credentials', 'true');
            return $response;
        }
    

    二、添加OpenRequest到\app\Http\Kernel.php里面去,这样才会生效。

    //1、如果是全局开启跨域,则添加到 $middleware 
       /**
         * The application's global HTTP middleware stack.
         *
         * These middleware are run during every request to your application.
         *
         * @var array
         */
     protected $middleware = [
                    ...
                OpenRequest::class,
                  ...
                        ]
    //2、如果你只是想给某些路由开启跨域,则添加到 $routeMiddleware 中去
    /**
         * The application's route middleware.
         *
         * These middleware may be assigned to groups or used individually.
         *
         * @var array
         */
        protected $routeMiddleware = [
                  ...,
            'openrequest'=>OpenRequest::class,
                  ...
                          ]
    
    

    三、绑定到控制器,控制器下所有的方法路由都回经过该中间件,需要重写控制器的__construct() 方法。

      public function __construct()
        {
            $this->middleware("openrequest");
        }
    

    四、如果仅对个别路由开启跨域,可以直接绑定到路由上。

    Route::get('/test','xxxx@xx')->middleware('openrequest')
    

    1、对于post的坑 以axios为例子,post需要添加请求头

    this.axios.post('/api/admin/login',{admin:"Martain"},{
            header:{
              'Content-Type': 'application/x-www-form-urlencoded'
            }
          }).then(response=>{
              console.log(response.data);
            }).catch(response=>{
                    console.log(response);
                });
    

    跨域在后端设置就行,前端中如果用到withCredentials: true,那么后端需要设置response.setHeader("Access-Control-Allow-Credentials", "true");才能使cookie携带上来,同时,Access-Control-Allow-Origin这个白名单需要设置当前前端访问时的浏览器上的域名或ip。

    //文件上传
    问题讨论:post请求Content-type到底该不该设置
    我得出的结论是,要正确设置。fetch 发送post字符类请求时,

    非文件上传时,无关你发送的数据格式是application/x-www-form-urlencoded或者application/json格式数据,你不设置请求头,fetch会给你默认加上一个Content-type = text/xml类型的请求头,有些第三方JAX可以自己识别发送的数据,并自己转换,但feth绝对不会,不行,你可以试一下;

    文件上传请求时,因为不知道那个boundary的定义方式,所以就如建议的一样,我们不设置Content-type。
    注:我用element-ui upload 上传图片时,遇到很多坑,我找了无数的header,都不行,最后发现说不要设置,就真的好了

    相关文章

      网友评论

        本文标题:对于 Laravel 路由请求跨域问题的解决方案

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