交响乐4。仅在静态文件中缺少 ACAO headers

Symfony4. Missing ACAO headers only in static files

我在 /api 上下文中安装了 Symfony Rest API,一切正常。此外,我在 /public/uploads 目录中托管静态 pdf 文件。通过前端浏览器获取文件路径时抛出错误

Access to fetch at 'http://127.0.0.1:8000/uploads/b8b3a04a69f59a6c20c9c153281657d5.pdf' from origin 'http://192.168.8.111:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

好像 nelmio cors 没有将 Access-Control-Allow-Origin header 添加到下载的文件中,但整个 api 工作正常没有问题。我没有覆盖 headers.

的 .htaccess 文件
nelmio_cors:
    defaults:
        origin_regex: true
        allow_origin: ['%env(CORS_ALLOW_ORIGIN)%']
        allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
        allow_headers: ['Content-Type', 'Authorization', 'origin', 'accept', 'bearer']
        expose_headers: ['Link']
        max_age: 3600
    paths:
        '^/uploads':
            allow_origin: [ '%env(CORS_ALLOW_ORIGIN)%' ]
            allow_methods: [ 'GET', 'OPTIONS' ]
            allow_headers: [ 'Content-Type', 'Authorization', 'origin', 'accept', 'bearer' ]
            max_age: 3600
        '^/': ~

allow_origin 在 .env

中设置为 '*'

当我 运行 CORS Chrome 扩展时一切正常。

您知道为什么 header 没有添加到文件中吗?

在这种情况下,当您直接下载文件时,您将绕过 PHP 应用程序,因此未添加 CORS headers。当然,您可以选择实现端点以从此文件夹下载文件。另一种选择是使用您的网络服务器 (Apache or Nginx) 添加所需的 headers。

解决方案

创建新的 apache 配置

<VirtualHost *:7777>
    DocumentRoot /var/www/html/document_repository

    Header always set Access-Control-Allow-Origin "*"
    Header always set Access-Control-Allow-Methods "GET, OPTIONS"
    Header always set Access-Control-Allow-Headers "origin"
    Header always set Access-Control-Expose-Headers "Content-Security-Policy, Location"
    Header always set Access-Control-Max-Age "3600"

    <Directory /var/www/html/document_repository>
        AllowOverride None
        Order Allow,Deny
        Allow from All
    </Directory>

    ErrorLog /var/log/httpd/document_repository_error.log
    CustomLog /var/log/httpd/document_repository_access.log combined
</VirtualHost>