Join the Stack Overflow Community
Stack Overflow is a community of 6.3 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I'm using angularJS to call a restfull API in symfony 2.

My angularJS app url is angular.me.dev My symfony2 api url is api.me.dev

I followed this tutorial to make my restfull api.

The problem is when I try to call this api

$http.({
    method: 'GET',
    url: 'http://api.me.dev/api/articles',
    headers: {
        'Authorization': 'Bearer ' + token
    }
})

An error occured: (here on google chrome):

XMLHttpRequest cannot load http://api.me.dev/api/articles. Response for preflight has invalid HTTP status code 405

(and on on firefox):

The Same Origin Policy disallows reading the remote resource

what did I find about this ?

Then I decide to allow headers, origin, ... on my server like this:

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

No change

I add to AngularJS

#coffee script
app.config ['$httpProvider', ($httpProvider) ->
    $httpProvider.defaults.useXDomain = true
    delete $httpProvider.defaults.headers.common['X-Requested-With']
]

Then I decided to install NelmioCorsBundle in my symfony api but I didn't see any change.

Finally, I notice a call works

$http.({
    method: 'GET',
    url: 'http://api.me.dev/api/articles',
})

Here the call return a 401 response (good, i need to be logged)

$http.({
    method: 'GET',
    url: 'http://api.me.dev/public/api/users',
})

Here I have a call doesn't need authorization, it works. I found only when I remove headers it works, and when I had any headers (content-type or authorization for example) an error occured.

Can anyone help me ? thanks !

share|improve this question
up vote 3 down vote accepted

Ok, my bad.

I said NelmioCors seems not working but i did something wrong.

I try again with nelmio cors bundle, using this configuration.

nelmio_cors:
    paths:
        '^/':
            allow_origin: ['http://angular.me.dev']
            allow_headers: ['Authorization', 'X-Requested-With', 'Content-Type', 'Accept', 'Origin', 'X-Custom-Auth']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE', 'OPTIONS']
            max_age: 3600

It's working ! NelmioCorsBundle resolve the problem.

https://github.com/nelmio/NelmioCorsBundle

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.