java - 语法错误: Unexpected token s in JSON at position 0 at JSON.解析+ angularjs

标签 java angularjs spring-mvc

我正在使用 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/

相关文章:

spring-mvc - spring webmvc映射jsp(不带 Controller )

java - 为什么 collections.sort 在 Java 中按比较器排序时会抛出不支持的操作异常?

javascript - 将数据参数(而不是查询参数)提供给 window.location.href ?创建动态文件

java - Spring 安全示例

javascript - bootstrap typeahead 指令不适用于输入字段

angularjs - 推送状态在 AngularJS 中显示错误

java - 配置数据源以将 Spring Security 集成到现有 Spring 项目中

java - 学习java中的Maps接口(interface),你能在同一个键上引用不同的值吗?

java - Tomcat Guice/JDBC 内存泄漏

java - 当 EditText 为空时防止 AlertDialog 关闭