2015-12-22 92 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。 –

相關問題