首页 > 解决方案 > Lumen 8 CORS 问题 2020 年 12 月

问题描述

我对使用 Lumen 8 的 CORS 有疑问。

我已经创建了 CorsMiddleware.php =>

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Response;

class CorsMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $headers = [
            // 'Access-Control-Allow-Origin' => getenv('ACCESS_CONTROL_ALLOW_ORIGIN'),
            // 'Access-Control-Allow-Methods' => getenv('ACCESS_CONTROL_ALLOW_METHODS'),
            'Access-Control-Allow-Origin' => '*',
            'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Credentials' => 'true',
            'Access-Control-Max-Age' => '86400',
            'Access-Control-Allow-Headers' => 'Content-Type, 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;
    }
}

在我的 bootstrap/app.php 中添加了它

$app->routeMiddleware([
    App\Http\Middleware\CorsMiddleware::class,
    'auth' => App\Http\Middleware\Authenticate::class,

]);

我什至添加到我的 .htaccess

Header set Access-Control-Allow-Origin "*" 
Header set  Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header set Access-Control-Allow-Credentials "true"

但和其他人一样没用......

奇怪的是,邮递员可以访问我的路线!?但是我的本地应用程序不能...

你们有什么想法吗?

标签: corslumen

解决方案


对于 Cors 中间件,我认为你应该在 $app->middleware([]) 中添加它。这是我们之前在项目中所做的。

$app->middleware([
    App\Http\Middleware\CorsMiddleware::class
]);

$app->middleware([]}是一个全局中间件,它确实非常有效,尤其是在处理 HTTP 请求时。

如果您想将中间件分配给特定的路由,您应该首先在 bootstrap/app.php 文件对$app->routeMiddleware(). 主要'auth' => App\Http\Middleware\Authenticate::class,是因为您处理路线而经过这里。因此,为了保护而进行身份验证。

#ref:https ://lumen.laravel.com/docs/5.4/middleware


推荐阅读