带有水果蛋糕的 Laravel CORS [英] Laravel CORS with Fruitcake
本文介绍了带有水果蛋糕的 Laravel CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用 laravel 后端制作 react 项目......我有一个 CORS 问题,我按照下面的链接做所有事情,配水果蛋糕.
I make react project with laravel Back-end ... I have a CORS problem, I do everything like on link below, with fruitcake.
API 的 Laravel 6 CORS 政策问题但仍然无法正常工作.
'paths' => ['api/*'],
/*
* Matches the request method. `[*]` allows all methods.
*/
'allowed_methods' => ['*'],
/*
* Matches the request origin. `[*]` allows all origins.
*/
'allowed_origins' => ['*'],
/*
* Matches the request origin with, similar to `Request::is()`
*/
'allowed_origins_patterns' => [],
/*
* Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers.
*/
'allowed_headers' => ['*'],
/*
* Sets the Access-Control-Expose-Headers response header.
*/
'exposed_headers' => false,
/*
* Sets the Access-Control-Max-Age response header.
*/
'max_age' => false,
/*
* Sets the Access-Control-Allow-Credentials header.
*/
'supports_credentials' => false,
而且,内核中间件是:
protected $middleware = [
AppHttpMiddlewareTrustProxies::class,
AppHttpMiddlewareCheckForMaintenanceMode::class,
IlluminateFoundationHttpMiddlewareValidatePostSize::class,
AppHttpMiddlewareTrimStrings::class,
IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class,
FruitcakeCorsHandleCors::class,
];
还有什么问题?
推荐答案
以下是使用 fruitcake/laravel-cors
时的一些问题:
Here are some gotchas when using fruitcake/laravel-cors
:
- 将
HandleCors
中间件放在app/Http/Kernel.php
中$middleware
的顶部:
- Put
HandleCors
middleware at the top of$middleware
inapp/Http/Kernel.php
:
protected $middleware = [
FruitcakeCorsHandleCors::class,
AppHttpMiddlewareTrustProxies::class,
AppHttpMiddlewareCheckForMaintenanceMode::class,
IlluminateFoundationHttpMiddlewareValidatePostSize::class,
AppHttpMiddlewareTrimStrings::class,
IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class,
];
把它放在底部或中间的某个地方是行不通的,因为请求可能会被其他具有更高优先级的中间件拒绝.
Putting it at the bottom or somewhere between won't work because requests might be rejected by other middlewares with higher priority.
- 不要不要死或退出控制器.
- Do NOT die or exit in controller.
例如以下将不起作用:
Route::get('/cors-test', function() {
dd("This won't work");
});
因为 FruitcakeCorsHandleCors::handle
方法添加了相关的 headers AFTER 处理请求:
Because FruitcakeCorsHandleCors::handle
method adds relevant headers AFTER handling request:
public function handle($request, Closure $next)
{
// --- omitted
// Handle the request
$response = $next($request); // <--- if you die here
if ($request->getMethod() === 'OPTIONS') {
$this->cors->varyHeader($response, 'Access-Control-Request-Method');
}
// you will never reach here
return $this->addHeaders($request, $response);
}
dump
也不起作用
- 更改
app/config/cors.php
后清除配置缓存:
- Clear config cache after changing
app/config/cors.php
:
$ php artisan config:cache
这篇关于带有水果蛋糕的 Laravel CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文