Laravel6.X 跨域問題解決方案

Jouzeyu發表於2019-12-26

簡要說明:新專案比較小,所以嘗試了6.0版本的Laravel框架。之前的專案用的是barryvdh/laravel-cors這個包,但是目前不支援6.X系統的,所以貼出這個專案的解決方案。

自定義中介軟體

第一步:建立中介軟體
php artisan make:middleware EnableCrossRequestMiddleware
第二步:編輯中介軟體
<?php
namespace App\Http\Middleware;
use Closure;
class EnableCrossRequestMiddleware{
    /**
     * @param $request
     * @param Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods:POST,GET,PUT,OPTIONS,DELETE'); // 允許請求的型別
        header('Access-Control-Allow-Credentials: true'); // 設定是否允許傳送 cookies
        header('Access-Control-Allow-Headers: Content-Type,Access-Control-Allow-Origin,Access-token,Content-Length,Accept-Encoding,X-Requested-with, Origin,Access-Control-Allow-Methods'); // 設定允許自定義請求頭的欄位

        return $next($request);

    }
}
第三步:註冊中介軟體(全域性)
<?php

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
      //other
        \App\Http\Middleware\EnableCrossRequestMiddleware::class,
    ];
本作品採用《CC 協議》,轉載必須註明作者和本文連結
空舟湖上~      ——Jouzeyu

相關文章