Laravel Cors middleware


Posted by JingTeng on 2020-09-16

太久沒做就會忘記,每次都要弄真的好麻煩喔,希望 Laravel 可以弄個預設 Cors middleware

step 1. make:middleware Cors
step 2. 設定 return header
step 3. 註冊 middleware
step 4. 設定 routes

step 1. make:middleware Cors

php artisan make:middleware Cors

產生在 app/Http/Middleware 裡

step 2. 設定 return header

允許所有來源

<?php
namespace App\Http\Middleware;
use Closure;

class Cors

{
    public function handle($request, Closure $next)
    {
      return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
        ->header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, X-Token-Auth, Authorization');
    }

}

step 3. 註冊 middleware

打開 app/Http/Kernel.php

protected $routeMiddleware = [
    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,

    'cors' => \App\Http\Middleware\Cors::class //加入 Cors::class
];

step 4. 設定 routes

Route::group([
        'middleware' => ['cors'],
    ], function ($router) {

    // middleware cors 保護的 route:
        Route::get('/hi', function () {
            return '{"hi":"hi"}';
        });
});

#Laravel







Related Posts

Day03 : 字典、集合

Day03 : 字典、集合

漫談傳輸介面-PATA

漫談傳輸介面-PATA

你是不是也被這個網路現象愚弄了?揭露發錯答案背後的科學真相!

你是不是也被這個網路現象愚弄了?揭露發錯答案背後的科學真相!


Comments