I am facing an issue with my AngularJS web application where it seems to be sending JSON correctly to the Tomcat server, but the server ends up receiving null values. I have looked at this question and this question for a solution, but they didn't help as expected. Edit: A comment pointed out that I misread the presence of the @RequestBody
notation.
Here is the relevant server method:
@PostMapping(path="/kind/add")
public @ResponseBody String addNewKind(Kind kind) throws Exception {
if (kind.getName() == null) {
throw new Exception("Name not found.");
}
kindRepository.save(kind);
return "Saved";
}
Here is the structure of the Kind object being sent:
@Entity
public class Kind {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
@OneToMany(mappedBy="kind")
private Set<Card> cards;
// Getters and setters omitted for brevity
}
This is the request function in my code:
var uri = 'http://localhost:8080/catalog/api/kind/';
function create(name) {
var deferred = $q.defer();
var data = {
'name': name
};
$http({
method: 'POST',
url: uri + 'add',
data: angular.toJson(data),
headers: {
'Content-Type': 'application/json; charset=UTF-8'
}
}).then(function(response) {
deferred.resolve(response.data);
}).catch(function(error) {
console.error('Error while adding kind');
deferred.reject(error);
});
return deferred.promise;
}
This is the JSON payload being sent to the server:
{"name":"Something"}
N.B. Sending additional parameters like `id` or `cards` also results in the same problem, despite them being optional:
{"id":0,"name":"Something","cards":[]}
The request headers look like this:
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Length: 20
Content-Type: application/json; charset=UTF-8
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/57.0
// Other headers truncated for clarity
Upon debugging, the server receives the following values for the `kind` object:
kind= Kind
cards= null
id= 0
name= null