【问题标题】:CORS Problem in lumen/laravel with headers set带有标题集的流明/laravel中的CORS问题
【发布时间】:2021-03-16 14:22:00
【问题描述】:

我正在开发一个新的 lumen 项目,我正在尝试通过一个 Angular 项目与它进行交流。 我添加了一个中间件,以使用中间件为本地请求添加以下标头:

$response->header('Access-Control-Allow-Origin', '*')
    ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
    ->header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, X-Token-Auth, Authorization');

但我仍然对 CORS 有疑问。

localhost/:1 Access to XMLHttpRequest at 'http://localhost:8080/auth/sign-in' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Request URL: http://localhost:8080/auth/sign-in
Request Method: OPTIONS
Status Code: 405 Method Not Allowed
Remote Address: [::1]:8080
Referrer Policy: strict-origin-when-cross-origin

我使用 php 内置服务器运行该项目,以前从未遇到过这样的问题。 我检查了中间件是否执行,这里没有问题,所以我没有任何想法。我在寻求帮助时发现的只是添加标头或服务器配置,所以没有帮助。

【问题讨论】:

    标签: laravel cors lumen


    【解决方案1】:

    这就是我的中间件的外观和工作正常:

    public function handle($request, Closure $next)
    {
        $headers = [
            'Access-Control-Allow-Origin'       => '*',
            'Access-Control-Allow-Methods'      => 'HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS',
            'Access-Control-Allow-Credentials'  => 'true',
            'Access-Control-Max-Age'            => '86400',
            'Access-Control-Allow-Headers'      => 'Origin, Content-Type, X-Auth-Token,  Accept, Authorization, X-Requested-With'
        ];
    
        if ($request->isMethod('OPTIONS')){
            return response()->json(['method' => 'OPTIONS'], 200, $headers);
        }
    
        $response = $next($request);
        foreach($headers as $key => $value) {
            $response->header($key, $value);
        }
    
        return $response;
    }
    

    试一试,也许会有帮助。

    附:请务必将请求发送到正确的 url。

    【讨论】:

    • 它工作了一会儿,几个小时后我又遇到了同样的错误。我不明白...(是的,这是正确的 URL)
    • @Kalika 如果它有效,则意味着这段代码一切正常。我的网络应用程序在这个中间件上运行良好。并发布所有错误,以便我或其他人可以帮助您!
    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 2020-12-05
    • 2021-03-05
    • 2018-11-08
    • 2019-02-05
    • 2017-06-14
    • 1970-01-01
    • 2021-03-09
    相关资源
    最近更新 更多