【问题标题】:JQuery Unsupported Media TypeJQuery 不支持的媒体类型
【发布时间】:2017-11-26 11:47:41
【问题描述】:

我的服务器 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 Unsupported media type

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");
        });
    });
}

你能告诉我什么是错的,并建议我如何做对

【问题讨论】:

    标签: jquery json jersey


    【解决方案1】:

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

    尝试添加

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

    在你之前signUp函数

    【讨论】:

    • 它可以工作,现在我处理错误的请求,因为我收到了空的用户名、密码和电子邮件。这意味着我无法发送查询参数
    • 我将收到的文本记录在服务器中,我得到了 username=hello&password=123&email=email 。如何将其解析为 json
    • 看这里它可能会帮助你弄清楚为什么它是查询字符串link1link2
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 2017-05-20
    • 1970-01-01
    • 2012-04-19
    • 2014-05-10
    • 2019-08-02
    相关资源
    最近更新 更多