JSON Stringify 400 Bad Request on AJAX POST

I get 400 Bad Request for the AJAX Post method. I am using Spring Data Recovery Services in Backend. Below is the code that I have on the front end for JS

var url = "/udb/data/SecurityRoleGroup", groupData = {id:"",name:"",accesslevel:"",roles:[]}; groupData.id = groupId.val(); groupData.name = groupName.val(); groupData.accesslevel = groupDescription.val(); groupData.roles = multiselect_to.val(); $.ajax(url, { type: 'POST', dataType: 'json', headers: { 'X-CSRF-Token': _csrfGroup.val(), 'Content-Type' : 'application/json' }, data: JSON.stringify(groupData), contentType: 'application/json', }) .done(function(results) { showMessage.html("Group details are saved successfully."); showMessage.removeClass().addClass("alert alert-success").show(); }) .fail( function(xhr, textStatus, errorThrown){ showMessage.html("Error : Rolegroup AJAX request failed! Please try again."); showMessage.removeClass().addClass("alert alert-danger").show(); }); 

Although I am serializing JSON data. However, I get a 400 Bad Request error. Could this error occur if any code violates the backend or its problem with the request sent to the server?

JAVA implementation

 @RepositoryRestResource(collectionResourceRel = "SecurityRoleGroup", path = "SecurityRoleGroup") public interface SecurityRoleGroupRepository extends PagingAndSortingRepository<SecurityRoleGroup, Long> { } 
+5
source share
2 answers

If you have spl characters in your data, you need to encode the data before sending it to the server. try it

 $.ajax(url, { type: 'POST', dataType: 'json', headers: { 'X-CSRF-Token': _csrfGroup.val(), 'Content-Type' : 'application/json' }, data: encodeURI(JSON.stringify(groupData)), contentType: 'application/json', }) 
+5
source

1. Why do you need to send a data conversion string that you can send, since it is 2. You do not need to specify the content type as application / json, since you defined it as json in the data type 3. if you use the post method here, make sure that you are processing the same on the server side.

0
source

All Articles