---
# System prepended metadata

title: Larave跨域處理
tags: [php]

---

---
title: Larave跨域處理
tags: php
---

1. 新增一個Middleware，並在```app\Http\Kernel.php```的全域middleware中註冊
```php=
protected $middleware = [
    ...
    \App\Http\Middleware\EnableCrossRequestMiddleware::class,
];
```

2. EnableCrossRequestMiddleware的handle中撰寫需要允許的網址
```php=
public function handle($request, Closure $next)
{
    $allowedOrigins = ['https://url1', 'https://url2'];

    $response = $next($request);
    if (!empty($_SERVER['HTTP_ORIGIN']) && in_array($_SERVER['HTTP_ORIGIN'], $allowedOrigins)) {
        $response->headers->set('Access-Control-Allow-Origin', $_SERVER['HTTP_ORIGIN']);
        $response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS, DELETE');
        $response->headers->set('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN');
        $response->headers->set('Access-Control-Allow-Credentials', 'true');
    }

    return $response;
}
```
