2

I am working with springmvc and angularjs. I'm trying to send the String response from springmvc controller to the angular controller, but facing the below error message shown on the browser console and the response which returned from springmvc is not getting printed in the angularjs side.

ERROR:

SyntaxError: Unexpected token s in JSON at position 0
at JSON.parse ()

Sample code: 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:

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";

}

In my above spring controller code, i'm returning success string to angularjs controller, but in the browser the below error is displayed.

SyntaxError: Unexpected token s in JSON at position 0 at JSON.parse ()

Note: Above is only the sample code , it is perfectly hitting the spring controller and issue is only while catching the response from spring controller to angular controller. I tried to change produces=MediaType.TEXT_PLAIN_VALUE to produces={"application/json"} but still it is showing the same error.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
nan
  • 191
  • 3
  • 10
  • JSON.parse has a problem in parsing string in objects. You might considering using return type as `@RequestMapping(value = "/allInfo", method = ReaquestMethod.POST, produces = MediaType.TEXT_PLAIN_VALUE) public @ResponseBody ResponseEntity allInfoData(@RequestParam("data") String data,@RequestParam("file") List files){ //logic return new ResponseEntity("success",HttpStatus.OK); }` – Sagar Kharab Jul 10 '18 at 03:16
  • https://stackoverflow.com/questions/3066886/json-parse-string-with-quotes Also refer this – Sagar Kharab Jul 10 '18 at 03:17
  • have a try by `response.text()` since it's plain string – Hearen Jul 10 '18 at 04:19
  • It seems server response is plain/text, and your Angular code assume a application/json. Changing `produces = MediaType.TEXT_PLAIN_VALUE` to `produces=MediaType.APPLICATION_JSON_VALUE` may be helpful. – tsh Jul 10 '18 at 06:08

3 Answers3

1

To avoid parsing the string, use 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;
    };

Also avoid using the deferred Anti-Pattern.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
0

In the response there are some values which are simple text not String so You're asking it to parse the JSON text something (not "something"). That's invalid JSON, strings must be in double quotes.

If you want an equivalent to your first example:

var s = '"something"';
var result = JSON.parse(s);
Alien
  • 15,141
  • 6
  • 37
  • 57
-1

The best solution is use responseType: "text" as "json" it will woke