Light 8 HEART 2020 年 12 月号

Lumen 8 CORS issue Decemeber 2020

我对使用 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"

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

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

你们有什么想法吗?

对于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