HTTP状态415 –不支持的媒体类型错误

时间:2018-10-30 09:56:18

标签: java angularjs spring http http-status-code-415

原始服务器拒绝处理请求,因为有效负载的格式不受目标资源上此方法的支持。

控制器代码

@RestController
public class UserController
{
    @Autowired
    public IretrieveService retrieveService;

    @RequestMapping(value="/register", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public ModelAndView doRegister(@RequestBody UserBean userBean,BindingResult result)
    {
        ModelAndView view = new ModelAndView("index");
        System.out.println("username "+userBean.getUsername());
        if(!result.hasFieldErrors())
        {
            if(retrieveService.insert(userBean) != null)
            {
                System.out.println("done");
            }

        }   
        return view;

    }
}

角度js代码

<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller("UserController", ['$scope', '$http', function($scope, $http, httpPostService) {
 var self=this;
 self.userBean={username:''};
$scope.insertData = function()
{
    alert($scope.userBean.username);
     $http({
         method: "POST",
         url: "register",
         data: $scope.userBean.username
        }).then(function(response){
         console.log(response.status);
         console.log("in success");

     }, function(response){
         console.log(response.status);
         console.log("in fail");     
     });
};
}]);
</script>


<form method="post" action="register" name="myForm">
      <label for="username" class="control-label">First Name:</label>
      <input type="text" data-ng-model="userBean.username" class="form-control"  placeholder="Enter Firstname"/>
       <button type="submit" data-ng-click="insertData()" class="btn btn-primary">Submit</button>
    </form>

出现错误,但没有将值从angular js传递给控制器​​类

2 个答案:

答案 0 :(得分:1)

由于控制器需要application / json,但您正在发送原始字符串数据,因此出现415 http错误。

这是如何发布json数据的有效示例:

Javascript:

var data = { "name":"emre" }
$.ajax({
    type: "POST",
    url: "http://localhost:8080/yourUrl",
    data: JSON.stringify(data),
    contentType: "application/json",
    cache: false,
    timeout: 600000,
    success: function (data) {
        alert("success")
    },
    error: function (e) {
        alert("ERROR : ", e);
    }
});

控制器:

@CrossOrigin
@PostMapping
public ResponseEntity post(@RequestBody UserBean request) {
    return ResponseEntity.status(HttpStatus.CREATED).body(request); // your response

}

UserBean类:

@Data // comes from lombok for getter setter purpose
class UserBean {
    private String name;
}

您可以根据需要调整控制器和javascript。

答案 1 :(得分:0)

在我看来,您发送到控制器的数据是String而不是UserBean对象。您的有效载荷为$scope.userBean.username,但您的控制器希望使用@RequestBody UserBean userBean

将控制器更改为

    public ModelAndView doRegister(@RequestBody String userName, BindingResult result)

可能会解决问题。