公共文件的 Laravel CORS 问题

Hap*_*der 1 php apache cors laravel

我正在尝试从 Angular 访问日志文件 URL,但它显示以下错误:

Access to XMLHttpRequest at 'https://myurl.com/storage/rmlogs/MyFileNameDetail.log' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Run Code Online (Sandbox Code Playgroud)

所有 API 请求都运行良好,错误仅针对文件请求。我将我的文件存储在rmlogs目录中,该目录storage/app/public/rmlogs链接到公共文件夹。

API 代码库是 Laravel,文件存储在storage目录中。我可以通过浏览器和邮递员访问该文件。由于 URL 是公开可用的,因此它不需要我为其他 API 请求传递的身份验证令牌。

我有cors.php如下配置文件:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Cross-Origin Resource Sharing (CORS) Configuration
    |--------------------------------------------------------------------------
    |
    | Here you may configure your settings for cross-origin resource sharing
    | or "CORS". This determines what cross-origin operations may execute
    | in web browsers. You are free to adjust these settings as needed.
    |
    | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
    |
    */

    'paths' => ['api/*'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,

];
Run Code Online (Sandbox Code Playgroud)

并具有Cors.php如下所示的中间件:

<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
    return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    }
}
Run Code Online (Sandbox Code Playgroud)

Que*_*tin 6

通过这个博客

有一些可用的包允许将 CORS 标头添加到从 Laravel API 发送的响应中。他们通过将中间件应用于所有 API 的路由来实现。但是,这种中间件不适用于公共目录,而公共目录通常是用户头像图像等资源的存储位置。因此,当这些资源返回到浏览器时,它们没有应用必要的 CORS 标头。

因此,您需要使用其他方法应用标头。这可能是使用 HTTP 服务器的配置文件最容易完成的。

你已经标记了这个所以你可以设置:

Header set Access-Control-Allow-Origin "*"
Run Code Online (Sandbox Code Playgroud)

在您的配置文件中。

例如:

<Location "/storage/rmlogs/">
    Header set Access-Control-Allow-Origin "*"
</Location>
Run Code Online (Sandbox Code Playgroud)

你也可以把Header指令中的一个.htaccess文件,但不建议这样做:

如果您有权访问 httpd 主服务器配置文件,则应完全避免使用 .htaccess 文件。使用 .htaccess 文件会降低 Apache http 服务器的速度。您可以在 .htaccess 文件中包含的任何指令最好在 Directory 块中设置,因为它具有相同的效果和更好的性能。

如果您使用共享主机,则可能别无选择。