【问题标题】:Symfony3 and NelmioCors - on POST it does not workSymfony3 和 Nelmio Cors - 在 POST 上它不起作用
【发布时间】:2017-04-19 22:42:18
【问题描述】:

我在 Symfony3 下使用 NelmioCorsBundle,设置如下:

nelmio_cors:
        defaults:
            allow_credentials: false
            allow_origin: []
            allow_headers: []
            allow_methods: []
            expose_headers: []
            max_age: 0
            #hosts: []
            origin_regex: false
        paths:
            '^/api/':
                origin_regex: true
                allow_origin: ['*']
                allow_headers: ['X-Custom-Auth','Content-Type','X-Requested-With','Accept','Origin','Access-Control-Request-Method','Access-Control-Request-Headers','Authorization']
                allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
                expose_headers: []
                max_age: 3600
            '^/':
                origin_regex: true
                allow_origin: ['*']
                allow_headers: ['X-Custom-Auth']
                allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
                max_age: 3600
                hosts: ['^api\.']

GET 上运行良好,但是当我尝试与POST 一起使用时,我得到了

请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问 Origin 'http://localhost:8080'。

这个设置有什么问题?

【问题讨论】:

    标签: symfony cors http-headers nelmiocorsbundle


    【解决方案1】:

    我不确定,但是在你的路径中有^/api/,而在你的错误消息中只有http://localhost:8080。尝试将POST 控制器的路由更改为/api/something。让我知道它是否有效。


    更新:

    我不太了解 Nelmio Cors,但如果你不打算使用复杂的标头管理我建议的方法,在我的情况下是可行的(没有外部包):

    添加监听器:src/AppBundle/Listentes/CorsListener.php

    <?php
    namespace AppBundle\Listener;
    
    use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
    
    class CorsListener
    {
        public function onKernelResponse(FilterResponseEvent $event)
        {
            $responseHeaders = $event->getResponse()->headers;
    
            $responseHeaders->set('Access-Control-Allow-Headers', 'origin, content-type, accept');
            $responseHeaders->set('Access-Control-Allow-Origin', '*');
            $responseHeaders->set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, PATCH, OPTIONS');
        }
    }
    

    并在服务中注册:app/config/services.yml

    services:
        app.cors_listener:
            class:      AppBundle\Listener\CorsListener
            tags:
               - { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }
    

    我知道这不是您问题的确切答案,但希望它可以提供帮助。

    【讨论】:

    • 我认为 url 是来源而不是 api 端点不是问题
    猜你喜欢
    • 2017-03-23
    • 2018-11-06
    • 2019-06-26
    • 2016-12-23
    • 2021-03-31
    • 2016-12-20
    • 2016-03-14
    • 2018-06-29
    • 1970-01-01
    相关资源
    最近更新 更多