【发布时间】:2019-05-28 14:32:28
【问题描述】:
过去几个月,我一直在我的开发机器上本地使用 Angular(客户端)和 Laravel(API)应用程序,没有任何问题。几天前,我将应用程序(客户端和 api)上传到服务器,突然间我开始收到 CORS 错误:
从 'https://api.domain.pt/api/login' 访问 XMLHttpRequest 来源“https://client.domain.pt”已被 CORS 阻止 策略:对预检请求的响应未通过访问控制 检查:没有“Access-Control-Allow-Origin”标头出现在 请求的资源。
在开发之初,我也遇到了这些错误,因为我为客户端和 api(client.localhost 和 api.localhost)使用了不同的本地域,并最终解决了向我的 Laravel API 添加 CORS 中间件的问题:
public function handle($request, Closure $next)
{
//apply cors only to api routes
if (Request::segment(1) == 'api') {
header("Access-Control-Allow-Origin: *");
$headers = [
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers' => 'X-Requested-With, X-Auth-Token, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding, X-Login-Origin',
'Access-Control-Allow-Credentials' => 'true'
];
if ($request->isMethod("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);
}
} else {
$response = $next($request);
}
return $response;
}
所有路由都使用 CORS 中间件。当应用尝试发布到登录 api (/api/login) 时,它甚至不会进入 CORS 中间件。
为什么这是在本地而不是在服务器上工作?
【问题讨论】:
-
你是如何注册这个中间件的?明智的路线还是全球路线?
-
全局和路由明智。我很绝望:-\
标签: angular laravel cors laravel-passport laravel-5.7