or123456
or123456

Reputation: 2199

bad request with angularjs $http.post and spring restful

I have a method in server(with spring restful):

@RequestMapping(value = "/lastQuestions", method = RequestMethod.POST)
public List<QuestionEntity> getLastQuestions(@RequestParam("count") Integer count) throws SQLException {

    List<QuestionEntity> _result = _Impl.getLast(count);
    return _result;

}

in angularjs :

   var _url = 'http://localhost:8080/Tabaraee/service/question/lastQuestions';

        $http.post(_url,{count:10}).success(function(data, status, headers, config) {
            return data;
        }).error(function(data, status, headers, config) {
            return data;
        });

but get error :

"NetworkError: 400 Bad Request - http://localhost:8080/Tabaraee/service/question/lastQuestions"

response :

<html><head><title>Apache Tomcat/7.0.57 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 400 - Required Integer parameter 'count' is not present</h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u>Required Integer parameter 'count' is not present</u></p><p><b>description</b> <u>The request sent by the client was syntactically incorrect.</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/7.0.57</h3></body></html>

why ?

Upvotes: 3

Views: 4025

Answers (1)

Master Slave
Master Slave

Reputation: 28519

Provide your count value map as a string, from the angular docs

params – {Object.} – Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified.

so you have two options, either stringify the parameters

    $http.post(_url,JSON.stringify({count:10})).success(function(data, status, headers, config) {
        return data;
    }).error(function(data, status, headers, config) {
        return data;
    });

or, you can leave your client side code as is, in which case the parameters will be send as JSON inside a request body, and therefore you would have to change your server side to bind from the request body, by changing the @RequestParam to @RequestBody

@RequestMapping(value = "/lastQuestions", method = RequestMethod.POST)
public List<QuestionEntity> getLastQuestions(@RequestBody("count") Integer count) throws SQLException {

Upvotes: 2

Related Questions