0

Unable to figure out why this error. I am not using any JSON.parse() which is the likely cause for this error to occur from most of the posts I have seen.

I am using simple user-registration in angular:

$scope.addUser = function () {
    $scope.userData = {
        username: $scope.user.email,
        password: $scope.user.password
    };

    auth.signup($scope.userData, successAuth, function (error) {
        $rootScope.error = error;
        console.log("error: " , $rootScope.error);
    });
};

myApp.service('auth', function($http){
    return {
        signup: function(data,success, error){
            $http.post('mvc-dispatcher/registration/', data).success(success).error(error);
        }
    };
});

Spring rest being backend service:

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private SecurityService securityService;

    @Autowired
    private UserValidator userValidator;

    @RequestMapping(value = "/registration", consumes = "application/json", produces = "application/json", headers = "content-type=application/x-www-form-urlencoded", method = RequestMethod.POST)
    public ResponseEntity registration(@RequestBody User userBean, BindingResult bindingResult, Model model) {
        System.out.println("register 2");

        userValidator.validate(userBean, bindingResult);
        HttpHeaders headers = new HttpHeaders();

        if (bindingResult.hasErrors()) {
            return new ResponseEntity("user already exists", HttpStatus.CONFLICT);
        }

        userService.saveUser(userBean);
        securityService.autologin(userBean.getUsername(), userBean.getPassword());
        return new ResponseEntity(headers, HttpStatus.CREATED);
    }
}

When a user is already registered, I am sending a response string "user already exists" but in console, I am not able to catch the error response. Its printing SyntaxError: Unexpected token u in JSON at position 0

kittu
  • 6,662
  • 21
  • 91
  • 185

1 Answers1

1

The $http.post() function probably tries to decode your JSON because your datatype is JSON and your web service is accepting application/json as type. What i suggest to do is passing an json array to your code.

{
    valid: false,
    errors: ['User allready connected']
    value: []
}

or

{
    valid: true,
    error: [],
    value: [userdata]
}

you could simply encode an hashmap in json in your java and send them to the client.

Hopes it helps !

  • Nic
Nicolas
  • 8,077
  • 4
  • 21
  • 51
  • I did this and it worked: `if (bindingResult.hasErrors()) { Map errorResponse = new HashMap(); errorResponse.put("error", "user already exists"); return new ResponseEntity(errorResponse, HttpStatus.CONFLICT); }` – kittu Oct 16 '16 at 14:56
  • Thanks for the hint about hashmap – kittu Oct 16 '16 at 14:56