【问题标题】:Error 415 with ajax request (Spring)带有 ajax 请求的错误 415 (Spring)
【发布时间】:2018-06-10 17:55:26
【问题描述】:

我的 ajax 请求已发送但从未到达我的控制器,我收到 415 错误 ()

Ajax 请求

function likeAjax(mId) {
    var data = {}
    data["id"] = mId;

    $.ajax({
        type : "POST",
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        url : "/likeMessage",
        data : JSON.stringify(data),
        dataType : 'json',
        timeout : 100000,
        beforeSend :(xhr)=>{
            xhr.setRequestHeader(csrfheader,csrftoken); //for Spring Security
        },
        success : (data) =>{
            console.log("SUCCESS : ", data);
            alert(data);
        },
        error : (e)=> {
            console.log("ERROR: ", e);
        },
        done : function(e) {
            alert("DONE : " + e.toString());
            console.log("DONE");
        }
    });

控制器

@ResponseBody()
@RequestMapping(value = "/likeMessage", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public AjaxResponseBody likeWithAjax(@RequestBody() AjaxRequestBody request) {

    AjaxResponseBody result = new AjaxResponseBody();

    //some logic

    return result
}

AjaxRequestBody 和 AjaxResponseBody 类

private class AjaxRequestBody{
    int id;
}

private class AjaxResponseBody{
    String message;
}

我确定我遗漏了一些明显的东西,但我似乎无法弄清楚这一点。

感谢您的帮助

【问题讨论】:

    标签: ajax spring http-status-code-415


    【解决方案1】:

    从控制器方法中删除 ResponseBody() 注释。确保在 Controller 类中添加了 RestCONtroller 注解。

    在RequestMapping中添加produces = "application/json"

    【讨论】:

    • 用produce = "application/json" 更新了答案
    • 有趣,让我看看日志。同时,您可以尝试将数据:JSON.stringify(data) 作为数据:数据。此外,还有一个以 String 作为 Arguement 的后备方法来进一步分析。
    • 我得到的只是:状态 HTTP 415 – 不受支持的媒体类型,我已经尝试删除 JSON.stringify
    • 感谢您的帮助,但是这个问题不值得花时间和精力,我会另找方法做我想做的事
    猜你喜欢
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 2012-12-12
    相关资源
    最近更新 更多