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

Laravel 11:用中间件与bootstrap/app.php配置CORS仍允许所有源的问题

解决Laravel 11自定义CORS中间件不生效的问题

你的问题根源在于Laravel 11默认已经启用了内置的CORS中间件,它会优先设置响应头,直接覆盖你自定义中间件的配置,导致始终返回*。按以下步骤修改即可解决:

1. 移除Laravel默认的CORS中间件

在bootstrap/app.php中,先移除框架自带的HandleCors中间件,再添加你的自定义中间件:

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        // 移除默认CORS中间件,避免覆盖自定义配置
        $middleware->remove(\Illuminate\Http\Middleware\HandleCors::class);
        // 添加自定义CORS中间件
        $middleware->append(\App\Http\Middleware\Cors::class);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

2. 修正自定义CORS中间件,处理OPTIONS预检请求

浏览器发送跨域非简单请求前会先发送OPTIONS预检请求,需要直接返回CORS响应头,无需执行后续路由逻辑。修改你的App/Http/Middleware/Cors.php:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class Cors
{
    public function handle(Request $request, Closure $next): Response
    {
        // 直接处理OPTIONS预检请求
        if ($request->isMethod('OPTIONS')) {
            $response = new Response();
        } else {
            $response = $next($request);
        }

        // 设置CORS响应头
        $response->headers->set('Access-Control-Allow-Origin', 'http://localhost:8');
        $response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
        $response->headers->set('Access-Control-Allow-Headers', 'Content-Type, X-Auth-Token, Origin, Authorization');
        
        // 若需要允许携带Cookie等凭证,可添加以下配置(可选)
        // $response->headers->set('Access-Control-Allow-Credentials', 'true');

        return $response;
    }
}

验证修改

重启Laravel服务后,再次发送跨域请求,查看响应头中的Access-Control-Allow-Origin即可确认是否已设置为http://localhost:8。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 15:15:06