anonymous1983 / symfony2

Tuto symfony2
MIT License
0 stars 0 forks source link

Symfony2 REST API No 'Access-Control-Allow-Origin' #1

Open anonymous1983 opened 8 years ago

anonymous1983 commented 8 years ago

If you have same problem like No 'Access-Control-Allow-Origin' when you try to access Rest Api from another Uri, two solutions :

1- With configuration in your _.htaccess_ in web folder:

For this solution you need to activate headers_module in your list modules of apache server. After add this configuration :

<IfModule mod_headers.c>
    # Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Allow-Origin "http://localhost:9000"
</IfModule>

2- With bundle _NelmioCorsBundle_ :

For this solution you do not need to activate headers_module in your list modules of apache server.

2.1-After installed your bundle, require the nelmio/cors-bundle package in your composer.json and update your dependencies. $ composer require nelmio/cors-bundle

2.2-Add the NelmioCorsBundle to your application's kernel:

    public function registerBundles()
    {
        $bundles = array(
            ...
            new Nelmio\CorsBundle\NelmioCorsBundle(),
            ...
        );
        ...
    }

2.3-Configuration

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: ['X-Custom-Auth']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            max_age: 3600
        '^/':
            origin_regex: true
            allow_origin: ['^http://localhost:[0-9]+']
            allow_headers: ['X-Custom-Auth']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            max_age: 3600
            hosts: ['^api\.']
sdaoudi commented 8 years ago

+1