Laravel 多个域来源 CORS

Laravel multiple domain origin CORS

我想让 laravel 中的两个 CORS 域能够在本地和服务器上使用它,因此我不想将我的应用程序暴露给任何域。这就是我现在拥有的东西

public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', 'http://localhost:4200')
//            ->header('Access-Control-Allow-Origin', 'http://api.example.com')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE')
            ->header('Access-Control-Allow-Headers', 'Content-Type');
    }

我不能像我评论的那样做,也不能做数组

您可以只检查您所在的主机,然后发送匹配的 Access-Control-Allow-Origin 只为那个主机。

$request->getHttpHost() 将为您提供请求中使用的主机名 - 如果您只需要基于此进行区分,我们可能会忽略其他也是来源的一部分的内容(协议, port) 在这里,简单地把它做成

public function handle($request, Closure $next)
    {
        $origin = $request->getHttpHost() == 'localhost' ?
                    'http://localhost:4200' : 'http://api.example.com';

        return $next($request)
            ->header('Access-Control-Allow-Origin', $origin)
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE')
            ->header('Access-Control-Allow-Headers', 'Content-Type');
    }

当然你可以做得更多"sophisticated",如果你需要它来获得更多可能的来源(比如将主机名与一组可能的值相匹配,必要时考虑协议和端口),但如果你现在只需要这两个,基本上应该可以了。

您可以定义一组您想要允许的来源,然后检查传入请求是否是其中之一:

public function handle($request, Closure $next)
{
    $allowedOrigins = ['example.com', 'example1.com', 'example2.com'];
    $origin = $_SERVER['HTTP_ORIGIN'];

    if (in_array($origin, $allowedOrigins)) {
        return $next($request)
            ->header('Access-Control-Allow-Origin', $origin)
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE')
            ->header('Access-Control-Allow-Headers', 'Content-Type');
    }

    return $next($request);
}

@thefallen 的回答对我有用,我也遇到了@sergey 的同样问题,我是这样解决的。

public function handle($request, Closure $next)
{

  $allowedOrigins = [env('FRONTEND_ENDPOINT', 'http://localhost:8080'), env('WORDPRESS_ENDPOINT', 'http://localhost'), env('EXTRA_ENDPOINT', 'http://127.0.0.1')];

  if($request->server('HTTP_ORIGIN')){
    if (in_array($request->server('HTTP_ORIGIN'), $allowedOrigins)) {
        return $next($request)
            ->header('Access-Control-Allow-Origin', $request->server('HTTP_ORIGIN'))
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
            ->header('Access-Control-Allow-Headers', '*');
    }
  }


  return $next($request);

}

这样你也可以像这样在 .env 文件中设置变量。

FRONTEND_ENDPOINT=http://localhost:8080
WORDPRESS_ENDPOINT=http://localhost
EXTRA_ENDPOINT=http://127.0.0.1:8080

您可以添加到 TrustHosts.php 中间件而无需执行任何额外操作。

// app/Http/Middleware/TrustHosts.php
public function hosts()
{
    return [
        $this->allSubdomainsOfApplicationUrl(),
        'https://www.nexgi.com'
    ];
}

以上代码在 laravel 8.x 中运行良好,如果您是 运行 queue 或 supervisorctl 然后重新启动以反映更改。