2017-03-31 129 views
0

嘗試發送從angularjs到Spring MVC的數據,但仍將繼續得到415錯誤

app.controller('RegisterFormSubmitCtrl', ['$scope', '$http', '$location', function($scope, $http) { 

$scope.submit = function() { 

    var registerData = { 
     "email" : $scope.email, 
     "firstName" : $scope.firstName, 
     "lastName" : $scope.lastName, 
     "DoB": $scope.DoB = new Date(), 
     "password" : $scope.password 
    }; 

    console.log(registerData); 

    $http({ 
     method: 'POST', 
     url: "http://localhost:8080/home", 
     data: registerData, 
     headers: { 
      'Content-type': 'application/json, charset=UTF-8' 
     } 
    }).then(function successCallback(response) { 
    }, function errorCallback(response) { 

    }); 
}; }]); 

Spring MVC的控制器

@Consumes("text/html") 
    @RequestMapping(value = "/home", method = RequestMethod.POST) 
    public ResponseEntity<Void> afterRegister(@RequestBody RegisterUserRequest request){ 
     System.out.print("Register user: " + request.getFirstName()); 
     if(userManager.emailRegistered(request.getEmail())){ 
      return new ResponseEntity<>(HttpStatus.CONFLICT); 
     } 
     // checking with google datastore 
     else if(userManager.addUser(request.getEmail(), request.getPassword(), request.getFirstName(), request.getLastName(), 
       request.getDoB(), "User")) { 
      return new ResponseEntity<>(HttpStatus.CREATED); 
     } 
     return new ResponseEntity<>(HttpStatus.CONFLICT); 
    } 

RegisterUserRequest類

@Accessors(chain = true) 
@Data 
@NoArgsConstructor 
@AllArgsConstructor 
public class RegisterUserRequest { 
    @NotNull 
    private String email; 
    private String firstName; 
    private String lastName; 
    private Date DoB; 
    @NotNull 
    private String password; 
} 

錯誤:

Failed to load resource: the server responded with a status of 415 (Unsupported Media Type) 

我試過刪除@RequestBody表示法來擺脫錯誤,但然後控制器只收到從request null。 還試圖在映射添加produces='application/json',仍然有錯誤415

在依賴我添加後閱讀下面JSON:

<dependency> 
    <groupId>org.codehaus.jackson</groupId> 
    <artifactId>jackson-mapper-asl</artifactId> 
    <version>1.9.13</version> 
</dependency> 
<dependency> 
    <groupId>com.fasterxml.jackson.core</groupId> 
    <artifactId>jackson-databind</artifactId> 
    <version>2.8.6</version> 
</dependency> 
+0

你可以發佈你的'RegisterUserRequest'類嗎? – hrdkisback

+0

我已經添加了'RegisterUserReques'類代碼 – Celeste

+0

添加這種依賴關係' \t \t \t org.codehaus.jackson \t \t \t 傑克遜核心 - 翔升 \t \t \t 1.9.13 \t \t'檢查。 – hrdkisback

回答

0

你的控制器afterRegister()方法現正接受text/html內容即@Consumes("text/html"),所以它更改爲@Consumes("application/json")

+0

我試過了,但仍然收到錯誤415 – Celeste

相關問題