0

My ajax request gets sent but never reaches my conrtroller, I get a 415 Error ()

The Ajax Request

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

The controller

@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
}

The AjaxRequestBody and AjaxResponseBody classes

private class AjaxRequestBody{
    int id;
}

private class AjaxResponseBody{
    String message;
}

I'm sure that I am missing something obvious but I can't seem to figure this one out.

Thank you for your help

benzi11
  • 3
  • 7

1 Answers1

0

Remove ResponseBody() annotation from the Controller Method. Make sure you have added RestCOntroller annotation in the Controller Class.

Add produces = "application/json" in RequestMapping

Prakash Ayappan
  • 455
  • 2
  • 8
  • Updated the answer with produces = "application/json" – Prakash Ayappan Jun 10 '18 at 18:24
  • Interesting, let me see the logs. Meanwhile, you could trydata : JSON.stringify(data) as data : data. Also, a fall back method with String as Arguement to analyse further. – Prakash Ayappan Jun 10 '18 at 18:41
  • all I get is : State HTTP 415 – Unsupported Media Type and i tried removing the `JSON.stringify` already – benzi11 Jun 10 '18 at 18:51
  • thank you for your help, but this problem is not worth the time nor the energy, I'll find another way to do what I want – benzi11 Jun 10 '18 at 19:18