简体   繁体   中英

Unsupported media type 415 in angularJS

I am trying to post the data, when I click on save I am getting 415 unsupported media type in the browser. One more observation I would like to add is, when I am sending data using POSTMAN to the application in JSON format then, the data is getting persisted in the database and is coming fine in the view. If using above angular code the issue still persists.

js code -

$scope.addUser = function addUser() {
var user={};
console.log("["+$scope.user.firstName+"]");
         $http.post(urlBase + 'users/insert/',$scope.user)
            .success(function(data) {
             $scope.users = data;   
             $scope.user="";
             $scope.toggle='!toggle';            
            });
        };

Controller code -

 @RequestMapping(value="/users/insert",method = RequestMethod.POST,headers="Accept=application/json")
     public @ResponseBody List<User> addUser(@RequestBody User user) throws ParseException {    
        //get the values from user object and send it to impl class
  }

Path variable can take only string values. you are passing "user" in path and in Controller method, addUser(), you are expecting of the type User class. As this is not a standard type like Integer or Float for which String to Integer converters are already available by default in Spring, you are expected to provide a converter from String to User.

You can refer this link for creating and registering converters.

As suggested by @Shawn, as you are posting an serialized object in request path, it is cleaner and better practice to pass it as request body. You can do something like the following.

@RequestMapping(value="/users/insert",method = RequestMethod.POST,headers="Accept=application/json")
public List<User> addUser(@RequestBody User user) throws ParseException { 
    //get the values from user object and send it to impl class
}

And pass user as request body in your ajax call. change js code to

//you need to add request headers
$http.post(urlBase + 'users/insert',JSON.stringify($scope.user)).success...

or

//with request headers
$http({
    url: urlBase + 'users/insert',
    method: "POST",
    data: JSON.stringify($scope.user),
    headers: {'Content-Type': 'application/json','Accept' : 'application/json'}
  }).success(function(data) {
         $scope.users = data;   
         $scope.user="";
         $scope.toggle='!toggle';            
        });
};  

Add these request headers Content-Type: application/json and Accept: application/json .
Similar issue posted on stackoverflow https://stackoverflow.com/a/11549679/5039001

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM