Learn how to deal with post request to your api in symfony with NelmioCorsBundle.

This problem is not caused by angular, the problem is by the configuration of nelmioCors bundle which doesn't allow POST request to your api properly.

If you are facing this issue, it's probably that you have NelmioCorsBundle in your symfony project to add cors-headers, otherwise you'll get a cross origin error.

To solve it change the allow_headers property of the path to your api to :

nelmio_cors:
    defaults:
        allow_credentials: false
        allow_origin: []
        allow_headers: []
        allow_methods: []
        expose_headers: []
        max_age: 0
        hosts: []
        origin_regex: false
    paths:
        # Important api settings :
        # Access-Control-Request-Method
        '^/api/':
            allow_origin: ['*']
            allow_headers: ['X-Custom-Auth','Content-Type','X-Requested-With','accept','Origin','Access-Control-Request-Method','Access-Control-Request-Headers','Authorization']
            allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
            max_age: 3600
        '^/oauth/':
            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\.']

allow_origin and allow_headers can be set to * to accept any value, the allowed methods however have to be explicitly listed. paths must contain at least one item.

Note: If you allow POST methods and have HTTP method overriding enabled in the framework, it will enable the API users to perform PUT and DELETE requests as well.

Then your request can be executed without any kind of problem :

$http.post('https://yoururl/api/user', {'userName': 'admin', 'password': 'test'}, {headers: {'Accept': 'application/json', 'Content-Type': 'application/json'}}).then(function success(response) {
    console.log(response);
});

Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors