【发布时间】:2018-07-10 03:03:01
【问题描述】:
我正在使用 springmvc 和 angularjs。我正在尝试将来自 springmvc 控制器的字符串响应发送到 angular 控制器,但是面对浏览器控制台上显示的以下错误消息,并且从 springmvc 返回的响应没有在 angularjs 端打印。
错误:
SyntaxError: 位置 0 处 JSON 中的意外标记 s
在 JSON.parse() 处
示例代码: js:
myApp.controller('myTestCtrl', function ($rootScope, $scope,MyService) {
$sco[e.submitInfo = function(){
var data = new FormData();
var allInfo =
{
'name': $scope.name,
'id': $scope.id,
'product': $scope.product,
'message':$scope.message
}
//files to be attached if exists
for (var i in $scope.filesAttached) {
var file = $scope.filesToAttach[i]._file;
data.append("file", file);
}
MyService.sendAllInfo(data).then(
function (response) {
if (response === "") {
alert("success");
//logic
}else{
alert("in else part " + response);
}},
function (errResponse) {
console.log("Error while retrieving response " + errResponse);
});
};
});
}});
我的服务:
myService.sendAllInfo = function (data) {
var deferred = $q.defer();
var repUrl = myURL + '/myController/allInfo.form';
var config = {
headers: {'Content-Type': undefined},
transformRequest: []
}
$http.post(repUrl,data,config)
.then(
function (response) {
alert("response json in service: "+ response);
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while getting response.data'+ errResponse);
deferred.reject(errResponse);
}
);
return deferred.promise;
};
Spring mvc:
@RequestMapping(value = "/allInfo", method = RequestMethod.POST, produces = MediaType.TEXT_PLAIN_VALUE)
public @ResponseBody
String allInfoData(@RequestParam("data") String data,@RequestParam("file") List<MultipartFile> files){
//logic
return "success";
}
在我上面的 spring 控制器代码中,我将成功字符串返回给 angularjs 控制器,但在浏览器中显示以下错误。
SyntaxError: 位置 0 处 JSON 中的意外标记 s 在 JSON.parse() 处
注意:以上只是示例代码,它完美地击中了弹簧控制器,问题只是在捕捉弹簧控制器到角度控制器的响应时。
我尝试将produces=MediaType.TEXT_PLAIN_VALUE 更改为produces={"application/json"},但仍然显示相同的错误。
【问题讨论】:
-
JSON.parse 在解析对象中的字符串时出现问题。您可能会考虑使用返回类型为
@RequestMapping(value = "/allInfo", method = ReaquestMethod.POST, produces = MediaType.TEXT_PLAIN_VALUE) public @ResponseBody ResponseEntity<String> allInfoData(@RequestParam("data") String data,@RequestParam("file") List<MultipartFile> files){ //logic return new ResponseEntity<String>("success",HttpStatus.OK); } -
试试
response.text(),因为它是纯字符串 -
似乎服务器响应是纯文本/文本,并且您的 Angular 代码假定为 application/json。将
produces = MediaType.TEXT_PLAIN_VALUE更改为produces=MediaType.APPLICATION_JSON_VALUE可能会有所帮助。
标签: java angularjs spring-mvc