簡體   English   中英

Angularjs Java Rest Service 415不支持的媒體類型

[英]Angularjs Java Rest Service 415 Unsupported Media Type

我正在使用java spring mvc和angular js。

我創建了一個休息服務:

@RestController 
public class UserApiController { 

@Autowired
private UserService userService;

@RequestMapping(value = "/users/createUser", method = RequestMethod.POST)
public @ResponseBody void addUser(@RequestBody UserRequestDTO newUser) {
    userService.addUser(newUser);
}

我的角度控制器是這樣的:

var newUser = { surname : "orozco", name: "daniel", password: "pepe", email:"dani@dani.com" };
$http.post(getCompletePath("users/createUser"), JSON.stringify(newUser))
    .success(function () {
         alert("ok");
    }).error(function () {    
    });

我的UserRequestDTO

public class UserRequestDTO {

private String email;

private String password;

private String name;

private String surname;

+獲取器和設置器

它返回以下錯誤:415(不支持的媒體類型)。

如果我發送的字符串不帶任何參數,它將起作用。 所以,問題出在參數

我不知道AngularJS,但嘗試在您的AngularJS代碼中添加Content-Type。 它應該看起來像這樣(根據規范https://docs.angularjs.org/api/ng/service/ $ http):

    var newUser = {
     surname : "orozco",
     name: "daniel",
     password: "pepe",
     email:"dani@dani.com" };
    var req = {
     method: 'POST',
     url: getCompletePath("users/createUser"),
     headers: {'Content-Type': 'application/json'},
     data: newUser};
    $http(req)
     .success(function () {alert("ok");})
     .error(function () {});

這可能是由於Content-Type標頭所致,請嘗試按如下所示明確包含它,

var req = {
 method: 'POST',
 url: getCompletePath("users/createUser"),
 headers: {
   'Content-Type': 'application/json'
 },
 data: {surname : "orozco", name: "daniel", password: "pepe", email:"dani@dani.com" },
}

$http(req).success(function(){...}).error(function(){...});

我忘記將org.codehaus.jackson包含在pom.xml中。 它解決了這個問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM