代码之家  ›  专栏  ›  技术社区  ›  Genaut

POST Ajax调用不发送JSON内容并获取不支持的媒体类型

  •  0
  • Genaut  · 技术社区  · 4 年前

    我有一个Java API 弹簧MVC . 我用Postman测试了一个端点,它运行良好(JSON类型的原始主体)。现在,我使用jQuery ajax调用从web页面测试同一个端点,看起来发送的格式是文本。

    这是我的ajax请求

    var jsonData = {
        "username" : $("#username").val(),
        "password" : $("#password").val()
    };
    console.log(jsonData);
    $.ajax({
        type: 'POST',
        url: "/app/sing-in",
        data: jsonData,
        contentType: "application/json",
        dataType: "json",
        success: function(data, textStatus, jqXHR){
            console.log("textStatus:" + textStatus);
            console.log("jqXHR:" + jqXHR.status);
        },
        error: function(jqXHR, textStatus, errorThrown){
            console.log("ERROR-textStatus:" + textStatus);
            console.log("ERROR-jqXHR:" + jqXHR.status);
        },
    });
    

    这是我收到的错误:

    timestamp: "2020-04-07T18:10:30.242+0000"
    status: 400
    error: "Bad Request"
    message: "JSON parse error: Unrecognized token 'username': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'username': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')↵ at [Source: (PushbackInputStream); line: 1, column: 10]"
    path: "/app/sing-in":
    

    奇怪的是,我并没有在请求中发送JSON对象,而是发送一个简单的文本。

    enter image description here

    可以用javascript对象代替JSON对象吗?我可以在这里进行泛型转换吗?

    1 回复  |  直到 4 年前
        1
  •  1
  •   Alien    4 年前

    尝试使用 JSON.stringify() 发送Ajax之前的数据。

    JSON.stringify(jsonData);
    

    更多信息请参考: https://stackoverflow.com/a/3987156/6572971