简体   繁体   中英

SYMFONY NELMIO CORS issue : Access-Control-Allow-Origin header contains multiple values

I created an API with symfony, FOSRestBundle and NelmioCorsBundle and I connect to it with a Ionic APP. some routes return me a CORS error:

Access to XMLHttpRequest at 'http://dev.myapp.com/api/login_check' fromfrom localhost/:1 origin 'http://localhost:8100' has been blocked by CORS policy: Response to the preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost/8100, *', but only one is allowed.

there is some part of my code:

config/nelmio_cors.yml:

nelmio_cors:
   defaults:
       allow_credentials: false
       allow_origin: []
       allow_headers: []
       allow_methods: []
       expose_headers: []
       max_age: 0
       hosts: []
       origin_regex: false
   paths:
       '^/api':
           allow_origin: ['*']
           allow_headers: ['*']
           allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
           max_age: 3600

I tried to add this in the .htaccess but without success:

   Header always set Access-Control-Allow-Origin: "*"
   Header always set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"

Someone have an idea about this problem? thanks you

Here is a working example:

nelmio_cors:
    defaults:
        allow_credentials: false
        allow_origin: []
        allow_headers: []
        allow_methods: []
        expose_headers: []
        max_age: 0
        hosts: []
        origin_regex: false
        forced_allow_origin_value: ~
    paths:
        '^/api/':
            allow_origin: ['*']
            allow_headers: ['Content-Type', 'Authorization']
            allow_methods: ['GET', 'OPTIONS', 'POST', 'PUT', 'PATCH', 'DELETE']
            max_age: 3600
        '^/':
            origin_regex: true
            allow_origin: ['%env(string:CORS_ALLOW_ORIGIN)%']
            allow_headers: ['X-Custom-Auth']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            max_age: 3600
            hosts: [ '^api\.' ]

Also your in your.env or.env.local:

CORS_ALLOW_ORIGIN='^https?://(localhost|127\.0\.0\.1)(:[0-9]+)?$'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM