Angular $http service - force not parsing response

2019-01-25 05:44发布

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?

2条回答
smile是对你的礼貌
2楼-- · 2019-01-25 05:58

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.

查看更多
老娘就宠你
3楼-- · 2019-01-25 06:10

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".

查看更多
登录 后发表回答