JQuery不支持的媒体类型

时间:2017-11-26 11:47:41

标签: jquery json jersey

我的服务器REST Jsersey接收Json和查询参数。我有3个查询参数:用户名,密码和电子邮件

@POST
    @Consumes({MediaType.APPLICATION_JSON})
    @Path("register")
    public Response register(@QueryParam("email") String email, @QueryParam("username") String userName, @QueryParam("password") String password) {
        System.out.println("username: " + userName);
        System.out.println("password: " + password);
        System.out.println("email: " + email);

        if (TextUtil.isEmpty(userName) || TextUtil.isEmpty(password) || TextUtil.isEmpty(email)) {
            return Response.status(Response.Status.BAD_REQUEST)
                    .header("Access-Control-Allow-Origin", "*")
                    .entity(ErrorUtil.badRequest("Field should not be empty")).build();
        }

        List<User> listUser = findAll();
        for(User user: listUser) {
            if (user.getUsername().equals(userName)) {
                return Response.status(Response.Status.BAD_REQUEST)
                        .header("Access-Control-Allow-Origin", "*")
                        .entity(ErrorUtil.badRequest("This username is already registered"))
                        .build();
            }
            if (user.getEmail().equals(email)){
                return Response.status(Response.Status.BAD_REQUEST)
                        .header("Access-Control-Allow-Origin", "*")
                        .entity(ErrorUtil.badRequest("This email is already registered"))
                        .build();
            }
        }

我尝试使用Jquery向服务器发送请求,但我得到了415不支持的媒体类型

var signUp = function () {
    $("#formSignUp").submit(function (e) {
      // var userName = $('#textUserNameSignUp').val();
      // var email = $('#textEmailSignUp').val();
      // var password = $('#textPasswordSignUp').val();

        e.preventDefault();

        $.post('http://localhost:43319/BR/webresources/users/register',
        { username: "hello", password : "123", email : "email"},
            function(returnedData){
              console.log(returnedData);
        })
        .fail(function(){
            console.log("error");
        });
    });
}

你能否告诉我错误的原因并建议我如何正确行事

1 个答案:

答案 0 :(得分:0)

您需要为要发送的数据指定contentType

尝试添加

$.ajaxSetup({
  contentType: "application/json; charset=utf-8"
});
signUp功能

之前

相关问题