简体   繁体   中英

Angular $http service - force not parsing response to JSON

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?

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 posted for this HTTP request.

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

You can also force angular to treat the response as plain text and not JSON:

$http({
    url: '...',
    method: 'GET',
    responseType: 'text'
});

This will make sure that Angular doesn't try to auto detect the content type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM