位于角度弹簧

时间:2016-10-16 14:28:58

标签: angularjs spring spring-restcontroller

无法弄清楚为什么会出现此错误。我没有使用任何JSON.parse(),这可能是我见过的大多数帖子发生此错误的原因。

我在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是后端服务:

@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);
    }
}

当用户已经注册时,我发送的响应字符串“user already exists”,但在控制台中,我无法捕获错误响应。它的打印SyntaxError: Unexpected token u in JSON at position 0

1 个答案:

答案 0 :(得分:1)

$ http.post()函数可能会尝试解码您的JSON,因为您的数据类型是JSON,而您的Web服务正在接受application / json作为类型。我建议做的是将json数组传递给你的代码。

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

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

你可以简单地在java中的json中编码一个hashmap并将它们发送到客户端。

希望它有所帮助!

  • 尼克