3

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 !

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.