带有ajax请求的错误415(Spring)

时间:2018-06-10 17:55:27

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

我的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;
}

我确信我错过了一些明显的东西,但我似乎无法想出这个。

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

从Controller方法中删除ResponseBody()注释。确保在Controller类中添加了RestCOntroller注释。

在RequestMapping中添加produce =“application / json”