You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular对接Laravel后端遇CORS问题:无Access-Control-Allow-Origin头

Angular对接Laravel后端CORS跨域问题排查

报错信息

Access to XMLHttpRequest at 'https://back-domain.com/api/login' from origin 'https://front-domain.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

已尝试的配置

  • 自定义Laravel CORS中间件:
<?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");
    }
}
  • Kernel.php多位置注册中间件:
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,
];
  • 路由级绑定cors中间件(也曾移除该配置)
  • .htaccess添加CORS头:
<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环境下,已按官方文档配置Nginx和Apache的CORS头

当前状态

  • 本地环境正常
  • PostMan调用生产后端接口正常
  • Angular生产环境前端仍报上述CORS错误
  • 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;
        })
    );
}

排查建议

  1. 优先处理OPTIONS预检请求
    当前中间件先执行业务逻辑再设置头,但OPTIONS预检请求可能在到达业务逻辑前被拦截,导致CORS头未生效。修改中间件逻辑:
public function handle($request, Closure $next)
{
    if ($request->isMethod('OPTIONS')) {
        return response()->json(['method' => 'OPTIONS'], 200)
            ->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");
    }

    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");
}
  1. 确认Plesk环境下Nginx/Apache配置优先级
    若Plesk中Nginx作为反向代理,需确保CORS头在Nginx层面生效,避免被Apache覆盖。在Plesk的「域名 > Apache & Nginx Settings > Additional Nginx directives」中添加:
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS';
add_header Access-Control-Allow-Headers 'Content-Type, Authorization, X-Requested-With';

if ($request_method = OPTIONS) {
    return 204;
}
  1. 清除浏览器缓存
    生产环境浏览器可能缓存旧的CORS响应头,强制刷新(Ctrl+Shift+R)或清空缓存后重试。

  2. 检查HTTPS证书有效性
    若后端HTTPS证书无效或不被浏览器信任,浏览器会隐藏真实错误,仅提示CORS问题。确认后端证书在浏览器中访问无警告。

  3. 避免重复配置冲突
    当前同时在Laravel中间件、.htaccess、服务器层面配置CORS,可能导致头重复或被覆盖。建议只保留一种配置方式(优先Nginx或Laravel中间件)。

内容的提问来源于stack exchange,提问作者byNethZ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 21:37:47