Reputation: 144
I am in the middle of learning react/redux and decided to take an old JQuery UI that makes request to Spring REST API and rewrite it in React. I am using Axios to make the request. In my old Query UI , I do the following when a form is submitted.
var formInputs = $(form).serialize();
$.post("/addAttrItem", formInputs, function(updated){
refresh();
showRecord(updated);
displayControlMsg("Record below was added successfully");
}
This is handled by the following code below in Spring
@ResponseBody
@RequestMapping(value="/someURL", method=RequestMethod.POST)
public AttrItem restfulAdd(AttrItem item) throws Exception
{
item.setLastUpdate(new java.util.Date());
itemService.create(item);
return item;
}
When sending the request through JQuery, AttrItem item param populated with all right values sent in by JQuery
However when I try the following axios
axios.post(someUrl, data).then
(res => {
dispatch(addAttributeSync(res));
}).catch(error =>{
alert('add item failed ' + error);
}
the AttrItem item param while not null itself, is empty with none of the fields set to values from the form. I confirmed that the data object contains right data prior to the post request.
Upvotes: 0
Views: 1825
Reputation: 144
The following seems to have resolved the issue. In React I added header config
return dispatch => {
var config = {
headers: { 'Content-Type': 'application/json' },
};
axios.post(someUrl, data).then
(res => {
dispatch(addAttributeSync(res));
}).catch(error =>{
alert('add item failed ' + error);
}
And I modified my Spring Controller endpoint to set the consumes and produces attribute as follows.
@ResponseBody
@RequestMapping(value="/attributeItem", method=RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public AttributeItem restfulAdd(@RequestBody AttributeItem attributeItem) throws Exception
{
attributeItem.setLastUpdate(new java.util.Date());
attributeItemService.create(attributeItem);
return attributeItem;
}
Upvotes: 0
Reputation: 1437
See if mapping the HTTP request body to the method argument item
using @RequestBody
annotation helps.
@ResponseBody
@RequestMapping(value="/someURL", method=RequestMethod.POST)
public AttrItem restfulAdd(@RequestBody AttrItem item) throws Exception
{
item.setLastUpdate(new java.util.Date());
itemService.create(item);
return item;
}
Upvotes: 2