最近忙于开发一个新项目,后端采用的是是laravel最新的框架laravel 12
, 前后端对接的时候出现了跨域的问题,这里说下解决方案,因为高版本直接内置了解决方案。
cors: https://laravel.com/docs/12.x/routing#cors
php artisan config:publish cors
编辑config/cors.php
,将其中的一些信息替换为自己的
<?php
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' => ['admin-api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => ['*'],
'allowed_headers' => ['*'],
'exposed_headers' => ['*'],
'max_age' => 86400,
// 前端axios对应的withCredentials也要设置为true
'supports_credentials' => true,
];
php artisan route:clear
php artisan config:clear
dd
, echo
, var_dump
都会导致cros失效,所以当你的配置没问题的时候,你可以顺着链路查看后端代码中是否存在对应的这些方法,建议debug的时候直接使用Log去记录。原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。