Symfony 4仅在静态文件中缺少ACAO标头

问题描述

我在/ 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标头添加到下载的文件中一样,但是整个api都可以正常工作而不会出现问题。我没有覆盖标题的.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','bearer' ]
            max_age: 3600
        '^/': ~

allow_origin在.env中的'*'上设置

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

您知道为什么不将标题添加文件吗?

解决方法

在这种情况下,当您直接下载文件时,您将绕过PHP应用程序,因此未添加任何CORS标头。当然,您可以选择实现端点以从该文件夹下载文件。另一个选择是使用您的Web服务器(ApacheNginx)添加必需的标头。

,

解决方案

创建新的Apache confing

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

Response