AJAX POST request for Spring MVC controller not working

I encountered an error:

Failed to load resource: server responded with status 415 (Unsupported media type)

Part of my AJAX code is as follows:

$.ajax({ url: '/authentication/editUser', type: "POST", contentType: "application/json", data: JSON.stringify(requestObj), //Stringified JSON Object success: function(resposeJsonObject) { // } }); 

And the controller handler method:

 @RequestMapping(value = "/editUser", method = RequestMethod.POST, headers = {"Content-type=application/json"}) @ResponseBody public EditUserResponse editUserpost(@RequestBody EditUserRequest editUserRequest) { System.out.println(editUserRequest); return new EditUserResponse(); } 

How to resolve the error?

+5
source share
4 answers

Manually set the Content-Type and Accept to the beforeSend handler of your AJAX function and remove the headers of your spring controller handler method so that it works like this:

AJAX Function:

 $.ajax({ url: '/authentication/editUser', type: 'POST', data: JSON.stringify(requestObj), //Stringified Json Object beforeSend: function(xhr) { xhr.setRequestHeader("Accept", "application/json"); xhr.setRequestHeader("Content-Type", "application/json"); } success: function(resposeJsonObject){} }); 

and a controller handler method like:

 @RequestMapping(value = "/editUser" , method = RequestMethod.POST) public @ResponseBody EditUserResponse editUserpost(@RequestBody EditUserRequest editUserRequest){ System.out.println(editUserRequest); return new EditUserResponse(); } 

See also :

+1
source

Change the AJAX call, add the headers:

 headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } 

Your general AJAX call should look like this:

 $.ajax({ url: '/authentication/editUser', type: "POST", headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } dataType: "json", data: JSON.stringify(requestObj), //Stringified JSON Object success: function(resposeJsonObject) { // } }); 

The Content-Type @RequestBody used by @RequestBody to determine the format for sending data.

0
source

I think you should try to remove the header in the controller as follows:

 @RequestMapping(value = "/editUser" , method = RequestMethod.POST) 
0
source

Try this .. I changed in the controller and jquery .. hope it works

 $.ajax({ url: '/authentication/editUser', type: "POST", contentType: "application/json", data: $("#FormName").serialize() success: function(respose) { // } }); 

And the controller handler method:

  @RequestMapping(value = "/editUser", method = RequestMethod.POST, headers = {"Content-type=application/json"}) // removed @RequestBody @ResponseBody public EditUserResponse editUserpost(EditUserRequest editUserRequest) { System.out.println(editUserRequest); return new EditUserResponse(); } 
0
source

Source: https://habr.com/ru/post/1215812/


All Articles