Angularjs 解析非 JSON POST 响应

Angularjs parsses non JSON POST response

我向服务器发送了一个 POST 请求。作为响应,服务器发送一个 http 代码和一个纯文本。

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

AngularJS 尝试解析对 json 的响应,但出现解析错误

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

这是我的Angular代码

$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)
});
} 

您需要重写变换响应函数

$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)
});
}