Search code examples
angularjsposthttp-status-code-400

AngularJS POST 400 bad request


I am trying to do a POST from an Angular controller, which works when my Java RestController is expecting no parameters (i.e. the signature for save below is just save()), but once I tell it to expect a parameter and try to send it in the POST request in Angular it fails with 400 Bad Request. Is there something that needs to be done to get data sent properly from an Angular POST?

@RestController
@RequestMapping("/person")
public class PersonController {

    @RequestMapping(method = RequestMethod.POST)
    public Person save(@RequestParam Long personnelId) {
        System.out.println("SUCCESSFULLY POSTED");
        return null;
    }
}

The POST request:

$http({
    url: 'http://localhost:8080/person',
    method: 'POST',
    data: {personnelId: 4}
}).success(function() {
    // do something on success    
});

This is going through Spring Security and Hibernate on server side, if that's relevant.


Solution

  • You may need to set your content type to application/json in your angular POST.

    $http({
        url: 'http://localhost:8080/person',
        method: 'POST',
        contentType: "application/json",
        data: {personnelId: 4}
    }).success(function() {
        // do something on success    
    });
    

    I'm guessing as I haven't really used Spring. Also check https://stackoverflow.com/a/26146813/559095