Angular $http 服务 - 强制不解析对 JSON 的响应 [英] Angular $http service - force not parsing response to JSON

查看:27
本文介绍了Angular $http 服务 - 强制不解析对 JSON 的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的服务器中有一个test.ini"文件,包含以下文本:

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

"[ALL_OFF]
 [ALL_ON]
"

我正在尝试通过 $http 服务获取此文件内容,这是我的功能的一部分:

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

此操作出现 Angular 异常(SyntaxError: Unexpected token A).
我打开了 Angular 框架文件,发现了异常:
因为文本文件内容以["开头并以]"结尾,Angular认为"这是一个JSON文件.

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.

这是 Angular 代码(1.2.23 版本中的第 7474 行):

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;
    }],

我的问题:

我如何强制角度进行此检查(if (JSON_START.test(data) && JSON_END.test(data))) 并且将文本响应解析为 JSON?

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

上面的函数替换了您为此 HTTP 请求使用 postet 的默认函数.

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

这篇关于Angular $http 服务 - 强制不解析对 JSON 的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆