英文:
I can get the token but CORS error display in secure route
问题
我想将Laravel与Angular集成。我可以获得令牌,因为我在cors.php中添加了以下内容:
'paths' => ['api/*', 'sanctum/csrf-cookie', 'oauth/*'],
但是其他安全路由不起作用(显示CORS错误)。我尝试使用中间件:
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');
我在Kernel.php中注册了它,并将其添加到Kernel中。最后,我在我的路由中添加了这个中间件:
Route::group(['middleware' => ['cors', 'json.response']], function () {
Route::get('/user', 'UserController@user')->middleware(['auth:api']);
});
但是我一直遇到CORS错误。有没有解决这个问题的办法?
英文:
I want to integrate Laravel with Angular. I can get the token becouse I ad this in cors.php
'paths' => ['api/*', 'sanctum/csrf-cookie', **'oauth/*'**],
But any another secure route doesn't work (display CORS error). I tryued use middleware
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');
I registered that in Kernel.php and I added that in Kernel. Finally I added this middleware in my routing
Route::group(['middleware' => ['cors', 'json.response']], function () {
Route::get('/user', 'UserController@user')->middleware(['auth:api']);
});
But all the time I have a cors error. Any Idea how can I solve this?
How solve the problem with cors?
答案1
得分: 0
尝试使用默认设置,然后如果需要,尝试进行修改。
不需要添加其他中间件,因为cors.php已经具有默认配置,由Laravel团队从Laravel 7引入。
英文:
Try with default settings and then try to modify it if necessary.
No need to add other middleware, cause cors.php has default configuration which introduced by Laravel Team from Laravel 7.
答案2
得分: 0
composer require barryvdh/laravel-cors
在 config/app.php
-> providers
Barryvdh\Cors\ServiceProvider::class,
然后在终端
php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"
最后在 app/Http/Kernel.php
protected $middlewareGroups = [
'web' => [
// ...
\Barryvdh\Cors\HandleCors::class,
],
'api' => [
// ...
\Barryvdh\Cors\HandleCors::class,
],
];
或者
>升级到 Laravel 的最新版本,该版本本身支持跨域问题
英文:
Install fruitcake/laravel-cors
composer require barryvdh/laravel-cors
In config/app.php
-> providers
Barryvdh\Cors\ServiceProvider::class,
Then in terminal
php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"
And finally in app/Http/Kernel.php
protected $middlewareGroups = [
'web' => [
// ...
\Barryvdh\Cors\HandleCors::class,
],
'api' => [
// ...
\Barryvdh\Cors\HandleCors::class,
],
];
Or
>Upgrade to latest version of Laravel, which support cross-issue by framework itself
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论