我有一个问题,我想知道我的错误在哪里:我想将 Angular 项目连接到 Laravel,但我收到此错误:“访问 XMLHttpRequest at 'https://back-domain.com/来自源“https://front-domain.com”的 api/login' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:不存在“Access-Control-Allow-Origin”标头所请求的资源。”
我在文件 proyectolaravel/app/Http/Middleware/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)
{
return $next($request)
->header("Access-Control-Allow-Origin", "*")
->header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")
->header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
}
}
在文件 proyectolaravel/app/Http/Kernel.php 中,我定义了中间件如下(由于我所做的不同尝试,定义了 3 次):
protected $middleware = [
\App\Http\Middleware\CORS::class
];
protected $middlewareGroups = [
'web' => [
// ...
],
'api' => [
\App\Http\Middleware\CORS::class,
'throttle:60,1',
'bindings',
],
];
protected $routeMiddleware = [
"cors" => \App\Http\Middleware\CORS::class,
];
在文件 proyectolaravel/routes/api.php 中,路由位于 Route 类的中间件方法中:
Route::middleware(['cors'])->group(function () {
// protected routes
});
我还尝试将路由移到中间件方法之外,因为中间件已经全局定义。
在 .htaccess 文件中,我定义了以下内容:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "*"
Header set Access-Control-Allow-Methods "GET, PUT, POST, DELETE, OPTIONS"
Header set Access-Control-Max-Age "1000"
</IfModule>
服务器运行 Ubuntu 作为操作系统,并使用 Plesk 作为服务器管理员。我还尝试按照本页中的步骤在 Plesk 中定义 Nginx 和 Apache 的标头:https://support.plesk.com/hc/en-us/articles/12377597400087-How-to-set-up -Plesk-for-Linux 中的 CORS 跨源资源共享-
但是,我在生产中仍然遇到相同的 CORS 错误。
注意:本地一切工作正常(典型的“它在我的机器上工作”情况😅),但在生产中,当从 PostMan 进行测试时,服务器正确返回响应,但它无法在 Angular 前端工作。我在 Angular 项目中没有任何拦截器来修改标头,并且用于发送请求的服务具有以下结构:
login(user: ILogin): Observable<any> {
const headers = new HttpHeaders().set("Content-Type", "application/json");
return this.http
.post<IResponse>(`${environment.base_url}/login`, user, {
headers,
})
.pipe(
map((response) => {
if (response.head === "success") {
// calculate token expiration and save it to local storage
return response;
})
);
}
如果您能阐明我的错误可能出在哪里或者可能导致此 CORS 问题的原因,我将不胜感激。抱歉“文字墙”,非常感谢您的关注。