Angular $http service - force not parsing response to JSON

cheziHoyzer picture cheziHoyzer · Jan 4, 2015 · Viewed 21.4k times · Source

I have a "test.ini" file in my server, contain the following text:

"[ALL_OFF]
 [ALL_ON]
"

I'm trying to get this file content via $http service, here is part of my function:

  var params = { url: 'test.ini'};
 $http(params).then(
                 function (APIResponse)
                   {
                     deferred.resolve(APIResponse.data);
                   },
                    function (APIResponse)
                   {
                     deferred.reject(APIResponse);
                   });

This operation got an Angular exception (SyntaxError: Unexpected token A).
I opened the Angular framework file, and I found the exeption:
Because the text file content start with "[" and end with "]", Angular "think" that is a JSON file.

Here is the Angular code (line 7474 in 1.2.23 version):

 var defaults = this.defaults = {
    // transform incoming response data
    transformResponse: [function(data) {
      if (isString(data)) {
        // strip json vulnerability protection prefix
        data = data.replace(PROTECTION_PREFIX, '');
        if (JSON_START.test(data) && JSON_END.test(data))
          data = fromJson(data);
      }
      return data;
    }],

My question:

How can I force angular to not make this check (if (JSON_START.test(data) && JSON_END.test(data))) and not parse the text response to JSON?

Answer

Sebastian Barth picture Sebastian Barth · Jan 4, 2015

You can override the defaults by this:

$http({
  url: '...',
  method: 'GET',
  transformResponse: [function (data) {
      // Do whatever you want!
      return data;
  }]
});

The function above replaces the default function you have postet for this HTTP request.

Or read this where they wrote "Overriding the Default Transformations Per Request".