【问题标题】:Symfony4. Missing ACAO headers only in static filesSymfony4。仅在静态文件中缺少 ACAO 标头
【发布时间】:2021-01-22 05:08:00
【问题描述】:

我在 /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', 'Authorization', 'origin', 'accept', 'bearer' ]
            max_age: 3600
        '^/': ~

allow_origin 在 .env 中设置为 '*'

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

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

【问题讨论】:

    标签: symfony cors nelmiocorsbundle


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      解决方案

      创建新的 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>
      

      【讨论】:

        猜你喜欢
        • 2016-01-31
        • 1970-01-01
        • 2021-09-20
        • 1970-01-01
        • 2018-11-06
        • 2021-09-08
        • 2015-11-28
        • 2019-10-15
        • 2021-02-21
        相关资源
        最近更新 更多