2016-10-16 51 views
0

無法弄清楚爲什麼會出現此錯誤。我沒有使用任何JSON.parse(),這是我看到的大多數帖子發生這種錯誤的可能原因。JSON在位置0的意外令牌u角彈簧

我正在使用的角度簡單的用戶註冊:

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

彈簧其餘爲後端服務:

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

當用戶已經被註冊,我發送響應字符串「用戶已經存在「,但在控制檯中,我無法捕捉錯誤響應。它的打印SyntaxError: Unexpected token u in JSON at position 0

回答

1

$ http.post()函數可能會嘗試解碼您的JSON,因爲您的數據類型是JSON,並且您的Web服務正在接受application/json作爲類型。我建議做的是將json數組傳遞給你的代碼。

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

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

你可以簡單地用JSON編碼的HashMap的在Java,並將它們發送到客戶端。

希望它有幫助!

  • 尼克
+0

我沒有這和它的工作:'如果(bindingResult.hasErrors()){ 地圖<字符串,字符串>錯誤響應=新的HashMap(); errorResponse.put(「錯誤」,「用戶已經存在」); 返回新的ResponseEntity(errorResponse,HttpStatus.CONFLICT); }' – Satyadev

+0

感謝有關hashmap的提示 – Satyadev

相關問題