我坚持这个错误。我也检查了其他类似的问题。我有一个简单的angularjs / spring应用程序。请求提供200,但我在开发人员工具/ firebug中收到响应的JSON解析异常。服务器的响应是一个简单的字符串,我能够看到。我怀疑问题是angular将它解析为JSON。请帮帮我。
角度控制器:
var loginApp = angular.module('loginApp',[]);
loginApp.controller('loginController', ['$scope','$http',function($scope,$http) {
$scope.login = function(isValid) {
if(isValid){
var formData= {"username":$scope.username,"password":$scope.password};
$http.post('/suite/rest/dologin',formData).success(function(response){
console.log(response);
alert(response);
});
}
};
}]);
Spring控制器:
@RequestMapping(value = "/dologin", method = RequestMethod.POST)
public @ResponseBody String doLogin(@RequestBody final User user) {
String validateUser = "admin";
return validateUser;
}
错误消息:
Error: JSON.parse: unexpected character at line 1 column 1 of the JSON data
fromJson@http://localhost:8080/suite/extResources/Angular/angular.js:1352:9
defaultHttpResponseTransform@http://localhost:8080/suite/extResources/Angular/angular.js:10455:1
transformData/<@http://localhost:8080/suite/extResources/Angular/angular.js:10546:12
forEach@http://localhost:8080/suite/extResources/Angular/angular.js:322:11
transformData@http://localhost:8080/suite/extResources/Angular/angular.js:10545:3
transformResponse@http://localhost:8080/suite/extResources/Angular/angular.js:11343:21
processQueue@http://localhost:8080/suite/extResources/Angular/angular.js:16104:28
scheduleProcessQueue/<@http://localhost:8080/suite/extResources/Angular/angular.js:16120:27
$RootScopeProvider/this.$get</Scope.prototype.$eval@http://localhost:8080/suite/extResources/Angular/angular.js:17378:16
$RootScopeProvider/this.$get</Scope.prototype.$digest@http://localhost:8080/suite/extResources/Angular/angular.js:17191:15
$RootScopeProvider/this.$get</Scope.prototype.$apply@http://localhost:8080/suite/extResources/Angular/angular.js:17486:13
done@http://localhost:8080/suite/extResources/Angular/angular.js:11637:36
completeRequest@http://localhost:8080/suite/extResources/Angular/angular.js:11843:7
requestLoaded@http://localhost:8080/suite/extResources/Angular/angular.js:11776:1
用户类:
public class User implements Serializable {
@JsonProperty
private String username;
@JsonProperty
private String password;
public User(){
}
public User(String username, String password){
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
答案 0 :(得分:2)
您可以使用请求中的config
object显式设置响应类型。这将覆盖响应标题中Content-Type
所假设的处理。
$http.post('/suite/rest/dologin',formData,{responseType:'text'})
最终,解决方案是更改服务器端,以便它不会在标头中返回Content-Type: application/json
的响应。
答案 1 :(得分:1)
字符串json
不是有效的String validateUser = {"id": "admin"}
,因此解析它会引发错误
尝试返回类似的内容:
{{1}}