繁体   English   中英

angularJS中不支持的媒体类型415

[英]Unsupported media type 415 in angularJS

我正在尝试发布数据,当我单击“保存”时,在浏览器中得到415不支持的媒体类型。 我想补充的另一点观察是,当我使用POSTMAN以JSON格式向应用程序发送数据时,数据将持久保存在数据库中,并且在视图中运行良好。 如果使用上述角度代码,问题仍然存在。

js代码-

$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';            
            });
        };

控制器代码-

 @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
  }

路径变量只能采用字符串值。 您在路径中和控制器方法addUser()中传递“用户”,则期望类型为User类。 由于这不是像Integer或Float这样的标准类型,在Spring中默认情况下已经提供String到Integer的转换器,因此您应该提供从String到User的转换器。

您可以参考此链接来创建和注册转换器。

正如@Shawn所建议的那样,当您在请求路径中发布序列化对象时,将其作为请求主体传递是一种更干净和更好的实践。 您可以执行以下操作。

@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
}

并在ajax调用中将用户作为请求正文传递。 更改js代码为

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

要么

//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';            
        });
};  

添加这些请求标头Content-Type:application / json和Accept:application / json。
在stackoverflow上发布的类似问题https://stackoverflow.com/a/11549679/5039001

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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