user567
user567

Reputation: 3862

Angularjs parsses non JSON POST response

I send a POST request to a server. As response the server send a http code and a plain text.

return Response.status(200).entity("Started").build(); 

AngularJS try to parse the response to json and I get a parsing error

Error: JSON.parse: unexpected character at line 1 column 1 of the JSON data

This is my Angular code

$scope.submitForm = function() {
  var url = 'http://localhost:8080/Server/server/start';
  var request = $http({
    method: 'POST',
    url: url,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    transformRequest: function(obj) {
      var str = [];
      for(var p in obj)
        str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
      return str.join('&');
    },
    data: {name: $scope.name}}).then(function(html) {
    //success callback code
    //console.log(html)
}, function(html) {
   //error callback code
   //console.log(html)
});
} 

Upvotes: 1

Views: 480

Answers (1)

Ahmed Anwar
Ahmed Anwar

Reputation: 51

You need to override transform response function

$scope.submitForm = function() {
  var url = 'http://localhost:8080/Server/server/start';
  var request = $http({
    method: 'POST',
    url: url,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    transformRequest: function(obj) {
      var str = [];
      for(var p in obj)
        str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
      return str.join('&');
    },
    transformResponse: [
     function (data) {
       return data;
     },
    ],
    data: {name: $scope.name}}).then(function(html) {
    //success callback code
    //console.log(html)
}, function(html) {
   //error callback code
   //console.log(html)
});
} 

Upvotes: 1

Related Questions