Laravel 5.x設置跨域訪問

作api接口的時候碰到個問題,跨域!
解決方法有不少,可是方便的依舊那麼一兩個,這裏我就介紹我最會的就是如下這種php

最方便的,新建一個middleWare,把這個middleware加入到全局中間件,全部的請求,都會通過這個中間件的過濾。

php artisan make:middleware CrossHttp

而後就會在appHttpMiddlewareCrossHttp.php這個中間件,在handle方法裏面添加以下代碼:api

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');  //ession共享的需求才用到
        return $response;
    }

這個*意思就是容許全部域名來訪問這個接口。
到這裏還沒完,中間件創建了,咱們還要加到appHttpKernel.php裏面去,否則不能生效。 跨域

clipboard.png

相關文章
相關標籤/搜索