【发布时间】:2016-06-21 18:08:57
【问题描述】:
我一直坚持这个错误。我也检查了其他类似的问题。我有一个简单的 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);
});
}
};
}]);
弹簧控制器:
@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;
}
}
【问题讨论】:
-
那个“简单字符串”到底是什么样的?哦,等等,我看到了。那么文本
admin绝对不是有效的JSON。纯字符串值必须用双引号引起来。 -
请同时发布 JSON 数据和用户类
-
validateUser = "admin";是字符串,不是 json 对象。
-
validateUser = "{\"name\":\"admin\"}";也许有效
-
问题出在您的 Spring 方面。查看 spring 如何返回字符串标题帖子类型
标签: javascript angularjs json spring