我正在使用 springmvc 和 angularjs。我正在尝试将 String 响应从 springmvc Controller 发送到 Angular Controller ,但是面对浏览器控制台上显示的以下错误消息,并且从 springmvc 返回的响应没有打印在 AngularJS 端。
错误:
SyntaxError: Unexpected token s in JSON at position 0
at 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 Controller 代码中,我将成功字符串返回到 angularjs Controller ,但在浏览器中显示以下错误。
SyntaxError: Unexpected token s in JSON at position 0 at JSON.parse ()
注意:上面只是示例代码,它完美地击中了 Spring Controller ,并且仅在捕获从 Spring Controller 到 Angular Controller 的响应时出现问题。
我尝试将 products=MediaType.TEXT_PLAIN_VALUE
更改为 products={"application/json"}
但仍然显示相同的错误。
最佳答案
要避免解析字符串,请使用 transformResponse: angular.identity
:
myService.sendAllInfo = function (data) {
̶ ̶v̶a̶r̶ ̶d̶e̶f̶e̶r̶r̶e̶d̶ ̶=̶ ̶$̶q̶.̶d̶e̶f̶e̶r̶(̶)̶;̶
var repUrl = myURL + '/myController/allInfo.form';
var config = {
headers: {'Content-Type': undefined},
transformRequest: [],
//IMPORTANT
transformResponse: angular.identity
}
var promise = $http.post(repUrl,data,config)
.then(
function (response) {
alert("response json in service: "+ response);
return response.data;
},
function(errResponse){
console.error('Error while getting response.data'+ errResponse);
throw errResponse;
}
);
return promise;
};
同时避免使用deferred Anti-Pattern .
关于java - 语法错误: Unexpected token s in JSON at position 0 at JSON.解析+ angularjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51256656/