Itsik Mauyhas
Itsik Mauyhas

Reputation: 3984

Angular - Unexpected token x in JSON at position 1 - response starts with [

I am sending $http request to my server and my response format is [SERVICE_NAME = XYZ][PRAMA = YZR], after the request finished I am getting this error:

SyntexError: Unexpected token S in JSON position 1 at Object.parse

I think it is because the response starts with [ , anyone jas faced and solved that problem? Here is my $http request:

  var promise = $http({method : 'GET', url : baseUrl, headers:{"Content-Type":text/html}, params:queryParams}).then(function(response){
       console.log(response);
       retuen response.data;
    }, function(error){
         console.log(error)
    })
   return promise;
};

I know my response is not a vaild JSON, still I need to parse it.

Thanks.

Upvotes: 1

Views: 2362

Answers (4)

steppefox
steppefox

Reputation: 1844

I'm not sure, but why your header is like: headers:{"Content-Type":text/html}, it looks wrong. Why not headers:{"Content-Type": 'text/html'}

Also, Content-type header indicates only encoding of your content, but not of the answer, try to add "Accept" header:

headers:{'Content-Type': 'text/html', 'Accept': 'text/plain'}

Here is the official W3C specification of protocols and headers https://www.w3.org/Protocols/rfc2616/rfc2616-sec14

Upvotes: 2

Ron Dadon
Ron Dadon

Reputation: 2706

Don't return your response with application/json content type. If your response have a Content-Type header with the value of application/json, Angular will automatically parse the JSON. Return your response with text/plain content type to avoid this.

Another option is to set the response transform function manually, for example:

$http({
  url: '...',
  method: 'GET',
  transformResponse: [function (response) {
      // Data response is plain text at this point
      // So just return it, or do your parsing here
      return data;
  }]
});

Upvotes: 3

Piyush.kapoor
Piyush.kapoor

Reputation: 6803

You have a spelling error in test/html

 var promise = $http({method : 'GET', url : baseUrl, headers:{"Content-Type":text/html}, params:queryParams}).then(function(response){
       console.log(response);
       retuen response.data;
    }, function(error){
         console.log(error)
    })
   return promise;
};

Upvotes: 0

Partha Sarathi Ghosh
Partha Sarathi Ghosh

Reputation: 11576

You need to configure from server side to send the data as text/plain This code can save you.

response.setContentType("text/plain");

Upvotes: 2

Related Questions