繁体   English   中英

AngularJs Spring MVC $http.post 错误 415(不支持的媒体类型)

[英]AngularJs Spring MVC $http.post Error 415 (Unsupported Media Type)

尝试将数据从 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>

您的控制器afterRegister()方法现在接受text/html内容,即@Consumes("text/html") ,因此将其更改为@Consumes("application/json")

尝试通过我的另一个答案检查您的 spring mvc 配置是否注册了 json 转换器

暂无
暂无

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

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