Angular $http 服务 - 强制不解析对 JSON 的响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27765309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:41:41  来源:igfitidea点击:

Angular $http service - force not parsing response to JSON

jsonangularjsparsinghttphttpresponse

提问by cheziHoyzer

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

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

"[ALL_OFF]
 [ALL_ON]
"

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

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

  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.

此操作出现 Angular 异常(语法错误:意外标记 A)。
我打开了 Angular 框架文件,我发现了一个例外:
因为文本文件内容以“ [”开头并以“ ]”结尾,Angular“认为”这是一个 JSON 文件。

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

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

 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 forceangular to notmake this check (if (JSON_START.test(data) && JSON_END.test(data))) and notparse the text response to JSON?

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

回答by Sebastian Barth

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.

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

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

或者读,他们写的“改变默认的转换每请求”。

回答by Ties

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

您还可以强制 angular 将响应视为纯文本而不是 JSON:

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

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

这将确保 Angular 不会尝试自动检测内容类型。