如果你要設定一支 API 是可以跨網域存取的,在 Laravel 11.x(好像是 9.x 之後版本就可以了),可以用以下方法:
首先生成 config/cors.php 的檔案
php artisan config:publish cors
裡面大概會長這樣:
return [ /* |-------------------------------------------------------------------------- | Cross-Origin Resource Sharing (CORS) Configuration |-------------------------------------------------------------------------- | | Here you may configure your settings for cross-origin resource sharing | or "CORS". This determines what cross-origin operations may execute | in web browsers. You are free to adjust these settings as needed. | | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS | */ 'paths' => ['api/*', 'sanctum/csrf-cookie'], 'allowed_methods' => ['*'], 'allowed_origins' => ['*'], 'allowed_origins_patterns' => [], 'allowed_headers' => ['*'], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => false, ];
再把 allowed_origins 改成要可以存取的網域就可以了,可以使用正規表達式定義規則,比如我要讓我 wingzero.tw 下的子網域都可以,就可以這樣寫:
'allowed_origins_patterns' => [ '~^https://.*\.wingzero\.tw$~', '~^https://wingzero\.tw$~', ],
給大家參考。