2015-12-22 189 views
1

我试图发布数据,当我点击保存时,我在浏览器中获取415不受支持的媒体类型。我想补充的另一个观察是,当我使用POSTMAN将数据以JSON格式发送到应用程序时,数据在数据库中持续存在,并且在视图中很好。如果使用上面的角码,问题仍然存在。在angularJS中不受支持的媒体类型415

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="https://stackoverflow.com/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 
    } 
+0

您正在发布一个对象作为uri的一部分。你很可能想把它作为身体的一部分。 –

回答

1

路径变量只能取的字符串值。您正在路径中传递“user”,并在Controller方法addUser()中传递类型为User的类。由于这不是像Integer或Float这样的标准类型,对于其中的字符串到整数转换器在Spring中默认已经可用,所以您需要提供从字符串到用户的转换器。

您可以参考此link创建和注册转换器。

正如@Shawn所建议的那样,当您在请求路径中发布序列化对象时,将它作为请求主体传递是更清洁和更好的做法。你可以做如下的事情。

@RequestMapping(value="https://stackoverflow.com/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:应用/ JSON和接受:应用/ JSON。
发表于Excelover的类似问题https://stackoverflow.com/a/11549679/5039001

+0

好吧,所以,我已经纠正了上面提到的,但现在在浏览器中获得'/ users/insert/415(Unsupported Media Type)'。控制器和上面提到的一样,js是'$ http.post(urlBase +'users/insert',$ scope.user)'。如何处理这个? – Harshit

+0

添加这些请求头Content-Type:application/json和Accept:application/json。将js代码更改为$ http.post(urlBase +'users/insert',JSON.stringify($ scope.user))。类似的问题发布在stackoverflow http://stackoverflow.com/a/11549679/5039001 –

+0

你不需要任何这些头,也不需要JSON.stringify()。角度为你做。只需传递该对象,$ http就会将其转换为JSON。 –

相关问题