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

地圖嵌入網頁- MapTiler 補

地圖嵌入網頁- MapTiler 補

在 oh-my-zsh 中自訂常用的 alias (重啟 terminal 後仍然有效)

在 oh-my-zsh 中自訂常用的 alias (重啟 terminal 後仍然有效)

前端工具 Gulp 與 Webpack 比較

前端工具 Gulp 與 Webpack 比較


Comments