Reputation: 141
I have a html form with some fields which I need to validate (name, address, email and etc). And it works, but I can't pass information about validation error from @PostMapping
method to AngularJS. The response is empty. What am I doing wrong?
Store.java - controller class
@Controller
public class Store {
@PostMapping("/save")
public ResponseEntity<Object> getShippingInfo(@Valid @RequestBody final User user,
final BindingResult bindingResult) {
Store.LOGGER.info("{}", user);
if (bindingResult.hasErrors()) {
Store.LOGGER.info("{}", "Validation failed");
final List<String> errors = bindingResult.getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toList());
return new ResponseEntity<>(errors, HttpStatus.OK);
} else {
Store.LOGGER.info("{}", "Validation successed");
}
return new ResponseEntity<>(HttpStatus.CREATED);
}
}
Main.js - file with AngularJS
var app = angular.module('myShoppingList', ['ngRoute', 'ngStorage']);
//some code
app.controller('myCtrl', function ($scope, $http, $location, items) {
$scope.listCustomers;
$scope.postFunc = function () {
if ($scope.formCust) {
$scope.listCustomers = this.formCust;
$scope.formCust = {};
}
var urlInfo = '/save';
var config = {
headers: {
'Content-Type': 'application/json',
'Accept': 'text/plain'
}
};
var dataArr = $scope.listCustomers;
$http.post(urlInfo, dataArr, config).then(function (response) {
$scope.postDivAvailable = true;
$scope.postCust = response.data;
}, function error(response) {
$scope.postResultMessage = 'Error Status: ' + response.statusText;
console.log('', $scope.postResultMessage);
});
$scope.listCustomers = [];
$scope.result = 'Success!';
};
});
So here my output in browser console from $scope.postResultMessage
is just empty, while from Store.LOGGER.info("{}", errors);
I get in Eclipse console as expected:
[size must be between 7 and 10, invalid credit card number]
Update 1
If i'm trying to output just response to browser console I'm getting this:
Upvotes: 0
Views: 145
Reputation: 4101
Problem might be that you return your errors with HTTP Status code 200. This means that front end error block is not executed (Frontend assumes everything is OK). You should set the HTTP status code to Bad Request for example.
Upvotes: 1