1

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.

adamconkey
  • 4,104
  • 5
  • 32
  • 61

2 Answers2

0

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

Community
  • 1
  • 1
Sid
  • 7,511
  • 2
  • 28
  • 41
  • I still get the same error. It does seem like it should be something with the type or the way in which the data gets transmitted though, since it only gives the error when data is being sent. – adamconkey Aug 10 '15 at 20:37
  • 1
    Yes, I think this may be the answer to your problem: http://stackoverflow.com/a/26146813/559095 – Sid Aug 11 '15 at 02:22
  • You would be right, that did end up resolving my problem. – adamconkey Aug 11 '15 at 13:41
  • @aconkey Thanks, please mark the answer correct in that case :) – Sid Aug 11 '15 at 15:44
  • As is it would be misleading to mark this the answer, the solution is in the other question that my question is now a duplicate of. If you were to copy out that code and put it here and indicate the question it came from, I could mark accepted answer. – adamconkey Aug 11 '15 at 16:02
0

aconkey

Have you tried mapping your param's name? @RequestParam(value="personnelId") Long personalId

Did you configure any CORS?

bobleujr
  • 1,179
  • 1
  • 8
  • 23
  • I think the name mapping is unnecessary since my parameter names match what I'm using in Angular, though I did try it and received the same error. What do you mean by configuring CORS? – adamconkey Aug 10 '15 at 21:24
  • It was just a guess that you may be using cross-origin and causing a bad request, may happen in some cases. Does the error provide you any other details? Although I believe your data format is fine, try changing to `$.param({personnelId: personnelId})` – bobleujr Aug 10 '15 at 23:10