1. 程式人生 > >前端跨域訪問--PHP設定(含laravel設定方法)

前端跨域訪問--PHP設定(含laravel設定方法)

目前實現js跨域請求的方法有兩種
1. jsonp
2. header設定allowList
這裡記錄一下使用第二種方法的相關設定。

php設定header,指定允許 http://www.test.com 跨域訪問。

header('Access-Control-Allow-Origin:http://www.test.com');
header('Access-Control-Allow-Credentials:false');

當然,可以把Access-Control-Allow-Origin 設定成 *,這樣是允許所有域名跨域訪問。

如果涉及到cookie(比如我的專案中有session共享的需求,前端需要在header中傳遞cookie資訊),此時需要把Access-Control-Allow-Credentials

設定成 true

如果是在laravel框架中,可以生成一箇中間件 Cors.php。(一般在 app/Http/MiddleWare 路徑下),修改handle 方法

public function handle($request, Closure $next)
    {
        $response = $next($request);
        $response->header('Access-Control-Allow-Origin', config('crm.domain.cors'));
        $response->header('Access-Control-Allow-Headers'
, 'Origin, Content-Type, Cookie, Accept, multipart/form-data, application/json'); $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS'); $response->header('Access-Control-Allow-Credentials', 'true'); return $response; }

然後修改Kenel.php,
- 全域性 : 在 $middleware

中新增一行 \App\Http\Middleware\Cors::class,
- 自定義 : 在 $routeMiddleware 中新增一行 : 'cors' => \App\Http\Middleware\Cors::class,需要的時候在對應路由中新增即可。