我正在使用 Spring Security 并尝试显示登录用户的 Angular 色。
Spring Sec 正在运行 - 我有工作注册和登录 JS 功能(我可以在数据库中看到新用户,并且我可以进行有效登录),但是当我尝试获取当前用户的 Angular 色信息并通过前端简单 html 文件中的简单 {{role}} 显示它时,我收到此错误:
但我仍然收到来自 JSON 的有效响应:
这是我的 user.html,其中 data-ng-init 和 {{role}} 是:
<div class="masthead">
<h4 class="text-center" data-ng-init="init()">
<strong>Users Home Screen</strong>
</h4>
<p>{{role}}</p>
<br>
...
</div>
这是我的 userController.js (它通过 app.js 连接到 user.html):
collectionsApp.controller('userController', function($scope, userService,
$state) {
$scope.init = function() {
userService.getAuthorization(displayRole);
}
displayRole = function(response) {
$scope.role = response.data;
}
});
我的userService.js:
collectionsApp.service('userService', function($http) {
return {
login : function(user, callback) {
$http.post('/user/login', user).then(callback);
},
register : function(user, callback) {
$http.post('/user/add', user).then(callback);
},
getAuthorization : function(callback) {
$http.get('/user/getAuthorization').then(callback);
}
};
});
我的 UserController.java(本文中仅显示感兴趣的函数):
@RequestMapping(value = "/getAuthorization", method = RequestMethod.GET)
public String getAuthorization() {
return SecurityContextHolder.getContext().getAuthentication().getAuthorities().toString();
}
哦,还有一件奇怪的事情: 当我设置断点(如下图所示)并在 user.html 上按 f5 时,调试就像永远不会到达断点一样,并在控制台中报告提到的 SyntaxError。如果你问我的话,那是相当超自然的……:)
最佳答案
您的响应不是有效的 JSON。如果将包含单个字符串元素“SOME_ROLE”的数组转换为 JSON,则会生成 ["SOME_ROLE"]
。如果您使用 Google 的 Gson 库,您可以执行以下操作:
Gson gson = new Gson();
gson.toJson(new String[]{SecurityContextHolder.getContext().getAuthentication().getAuthorities().toString()});
关于java - Object.parse 中的 JSON 意外标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25407527/