【问题标题】:SyntaxError: Unexpected token s in JSON at position 0 at JSON.parse + angularjsSyntaxError:JSON.parse + angularjs 位置 0 处的 JSON 中的意外标记
【发布时间】: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&lt;String&gt; allInfoData(@RequestParam("data") String data,@RequestParam("file") List&lt;MultipartFile&gt; files){ //logic return new ResponseEntity&lt;String&gt;("success",HttpStatus.OK); }
  • 试试response.text(),因为它是纯字符串
  • 似乎服务器响应是纯文本/文本,并且您的 Angular 代码假定为 application/json。将 produces = MediaType.TEXT_PLAIN_VALUE 更改为 produces=MediaType.APPLICATION_JSON_VALUE 可能会有所帮助。

标签: java angularjs spring-mvc


【解决方案1】:

为避免解析字符串,请使用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

【讨论】:

  • 感谢上帝的回答!
【解决方案2】:

在响应中有一些值是简单文本而不是字符串,因此您要求它解析 JSON 文本 something(不是 "something")。这是无效的 JSON,字符串必须用双引号括起来。

如果您想要与第一个示例相同的内容:

var s = '"something"';
var result = JSON.parse(s);

【讨论】:

    【解决方案3】:

    最好的解决方案是使用 responseType: "text" as "json" 它会唤醒

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多