php - 设置 cookie 时 Laravel CORS 不起作用
问题描述
我\Fruitcake\Cors\HandleCors
在 Laravel 应用程序中使用 CORS 中间件。
我的cors.php
文件如下所示:
'paths' => ['api/*', 'oauth/*', '*'],
'allowed_methods' => ['POST', 'GET', 'DELETE', 'PUT', '*'],
'allowed_origins' => ['http://localhost:3000', 'https://localhost:3000'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
我正在设置cookie作为响应:
$access_cookie = Cookie::make('access_token', $access_token, $cookieLife, null, null, true);
$refresh_cookie = Cookie::make('refresh_token', $refresh_token, $MINUTES_IN_ONE_YEAR, null, null, true);
return response()
->json(['tokens' => ['access_token' => $access_token, 'refresh_token' => $refresh_token], 'user' => $user])->withCookie($access_cookie)->withCookie($refresh_cookie);
最后,我从正在运行的 React 应用程序调用这个 api 端点https://localhost:3000
它给了我一个错误,说不允许 CORS(经典 CORS 错误)。
但是当我从响应中删除 cookie 时,它工作正常。
我还需要什么其他设置才能让它工作?
解决方案
不确定这是否是您要寻找的,但我使用的是 laravel 5.3,并且必须为从另一个应用程序对我的应用程序进行的 API 调用添加 CORS 支持,这就是我所做的。
在 app\Http\Middlewear 中,我创建了一个名为 Cors.php 的文件并将其放置在以下位置:
<?php namespace App\Http\Middleware;
use Closure;
class Cors {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
header("Access-Control-Allow-Origin: *");
// ALLOW OPTIONS METHOD
$headers = [
'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
];
if($request->getMethod() == "OPTIONS") {
// The client-side application can set only headers allowed in Access-Control-Allow-Headers
return Response::make('OK', 200, $headers);
}
$response = $next($request);
foreach($headers as $key => $value)
$response->header($key, $value);
return $response;
}
}
然后在我添加的受保护的 $routeMiddleware 内的 App\Http\Kernel.php
'cors' => \App\Http\Middleware\Cors::class,
然后在我的路线中,无论需要什么CORS,我都添加了中间件
Route::post('/my/api/call', 'MyController@MyApiRoute')->middleware(['cors']);
推荐阅读
- gojs - 从 Go js 中的 License Certificate No 中查找许可证密钥
- javascript - 多个 setTimeout:并行还是递归?
- arrays - var 和 := 在 slice 声明 go 语言中的区别
- html - Angular6根据构建配置更改站点日志
- php - 如何知道本地托管的 php 脚本加载时间
- python - Python argparse:传递没有参数名称的单个参数
- asp.net-core - Razor Pages 中 @page 指令中的强类型路由
- python - 我已经分配了我的变量,但输出显示:“分配前引用的局部变量”
- c++ - tensorflow C++ 相当于 tf.trainable_variables()?
- c++ - 在可变参数类模板中覆盖多个虚函数