Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

symfony2 REST, AngularJs access-Control-Allow-Origin

okay I am desperate. I am using FOSRestBundle and NelmioCorsBundle

I am still getting this error when I am trying to post data by angular from different server:

XMLHttpRequest cannot load 
http://IP/app_dev.php/api/v1/pages.json. 
No 'Access-    Control-Allow-Origin' header is present on the requested resource.
Origin      'http://127.0.0.1:9000' is therefore not allowed access.



Remote Address:IP:80
Request URL:http://IP/app_dev.php/api/v1/pages.json
Request Method:OPTIONS
Status Code:200 OK
Request Headers
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,sk;q=0.6,cs;q=0.4
Access-Control-Request-Headers:accept, authorization, content-type
Access-Control-Request-Method:POST
Cache-Control:no-cache
Connection:keep-alive
Host:192.168.43.195
Origin:http://127.0.0.1:9000
Pragma:no-cache
Referer:http://127.0.0.1:9000/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36

Response Headers
Access-Control-Allow-Headers:X-Requested-With, content-type
Access-Control-Allow-Methods:POST, GET, PUT, DELETE, OPTIONS
Connection:Keep-Alive
Content-Length:573
Content-Type:text/html; charset=iso-8859-1
Date:Sun, 29 Jun 2014 18:07:54 GMT
Keep-Alive:timeout=5, max=100
Server:Apache/2.4.7 (Ubuntu)

I am trying to fix it all day long...

Currently I have:

# CORS OPTIONS (add this too)
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
    Header always set Access-Control-Allow-Methods "POST, GET, PUT, DELETE, OPTIONS"
    Header always set Access-Control-Allow-Headers "X-Requested-With, content-type"
</IfModule>

nelmio_cors:
    paths:
        '^/api/':
            allow_origin: ['*']
            allow_headers: ['X-Custom-Auth']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE','OPTIONS']
            max_age: 3600

Sending as:

            var data = new FormData;
            data.append('title', 'title');
            data.append('body', 'body');

            var request = $http({
                method: 'POST',
                url: TB+"/app_dev.php/api/v1/pages.json",
                headers: {
                    'Authorization': 'Bearer '+User.getAccessToken(),
                    'Content-Type': 'application/json'
                },
                data: data
            });

Any idea what's wrong with it please?

screenshot from 2014-06-29 20 20 01

like image 321
Lukas Lukac Avatar asked Jun 30 '14 20:06

Lukas Lukac


1 Answers

I had a similar problem with NelmioCorsBundle, I solved with this settings:

nelmio_cors:
    paths:
        '^/api/':
            allow_origin: ['*']
            allow_headers: ['*']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE','OPTIONS']
            max_age: 3600
like image 101
Filo Avatar answered Sep 20 '22 16:09

Filo