Neeraj
Neeraj

Reputation: 58

How to send a post request data to spring rest controller using angular js

Here is my angularjs code

$http({
                method : "POST",
                url : '/jobseeker',
                data : {
                    "email" : $scope.userdata.uemail,
                    "firstname" : $scope.userdata.fname,
                    "lastname" : $scope.userdata.lname,
                    "password" : $scope.userdata.upassword
                }
            }).success(function(data) {
                console.log(data);
                //state.go(to verification page for job seeker
            })

and here is my rest controller mapping

@RequestMapping(value = "/jobseeker", method = RequestMethod.POST)
    public ResponseEntity signUp(@RequestParam("email") String email, 
                                 @RequestParam("firstname") String firstname,
                                 @RequestParam("lastname") String lastname,
                                 @RequestParam("password") String password) { ....}

I am getting 400 Bad request error stating that parameter email is missing

I also tried add the following headers in my code still I get the same error

headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }

Upvotes: 0

Views: 4548

Answers (2)

Peter
Peter

Reputation: 389

Better uses a model and get it in a @RequestBody.

For example :

class Model {
     public Model(){}

     String email; 
     String firstname;
     String lastname;
     String password;

     // getters/setters and constructor with parameters
}

then in controller...

signUp(@RequestBody Model model)...

good luck

Upvotes: 0

CrazyMac
CrazyMac

Reputation: 462

I am not sure if you fixed this issue but I am trying to post a standard way to do a POST from AngularJS but I am sure there are few other ways to do it.

In AngularJS, a function that will hold the POST call to Controller.

$scope.httpFunction = function() {
    var data = new FormData();
    data.append('email', $scope.userdata.uemail);
    data.append('firstname', $scope.userdata.fname);
    // Append as many parameters as needed
    $http.post('jobseeker', data, {
        withCredentials : false,
        transformRequest : angular.identity,
        headers : {
                'Content-Type' : undefined
        }
    }).then(function(response){
        // ANything you wanted to do with response
    })
}

Always ensure the number of parameters are matching and the param names are same in Angular and Controller

Upvotes: 1

Related Questions