【问题标题】:No 'Access-Control-Allow-Origin' header is present on the requested resource Symfony请求的资源 Symfony 上没有“Access-Control-Allow-Origin”标头
【发布时间】:2023-03-16 19:35:01
【问题描述】:

我想通过前端请求访问我的后端,但我总是收到以下错误: 从源“...”访问“...”处的 XMLHttpRequest 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”标头出现在请求的资源。

我已经尝试使用 Nelmio Bundle 并搜索了不同的地方,但没有任何效果。我主要遵循本教程: https://codereviewvideos.com/course/beginners-guide-back-end-json-api-front-end-2018/video/symfony-4-cors-json-api

我也尝试在我的函数中使用标题,但结果是相同的错误消息:

//Controller
      $response = new Response();
            $response->headers->set('Content-Type', 'application/json');
            $response->headers->set('Access-Control-Allow-Origin', '*');

//nelmio_cors.yaml:
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']
        expose_headers: ['Link']
        max_age: 3600
    paths:
        '^/': null

//.env File:

    ###> nelmio/cors-bundle ###
CORS_ALLOW_ORIGIN=^https?://.*?$
###< nelmio/cors-bundle ###

【问题讨论】:

  • 检查你的头模块是否启用。如果您使用的是 apache sudo a2enmod header 并使用 sudo service apache2 reload 重新启动您的 apache 服务器

标签: php symfony cors nelmiocorsbundle


【解决方案1】:

我发现 Azure 提供了一个内置功能来启用和管理 CORS。这个函数似乎覆盖了我试图在我的函数中使用的 CORS 包。因此,您只需转到 azure 门户 -> 您的应用服务 -> 并单击 CORS(在 API 下)

【讨论】:

    猜你喜欢
    • 2017-02-07
    • 2014-07-30
    • 2016-01-14
    • 2023-03-15
    • 2018-12-02
    • 2015-10-30
    • 2019-10-07
    • 2021-09-28
    • 2021-02-23
    相关资源
    最近更新 更多