4

In the latest release of Angular (v1.3.0) they added a fix for the content-type header for application/json. Now all my responses get an error cause they are not valid JSON. I know I should change the back-end to respond with a plain text header, but I can't control that at the moment. Is there any way for me to pre-parse the response before Angular tries to parse it?

i think that this was the fix they made: https://github.com/angular/angular.js/commit/7b6c1d08aceba6704a40302f373400aed9ed0e0b

The problem I have is that the response I get from the back-end has a protection prefix that doesn't match the one that Angular is checking for.

I have tried to add an http interceptor in the config, but that didn't help, still parses after Angular itself.

$httpProvider.interceptors.push('parsePrefixedJson');

The error i get in my console (it comes from the deserializing of a JSON string in Angular):

SyntaxError: Unexpected token w
at Object.parse (native)
at fromJson ...
KungWaz
  • 1,918
  • 3
  • 36
  • 61

2 Answers2

1

I found a way to change the default transformer by adding this to the Angular app:

app.run(['$http',
    function($http) {
        var parseResponse = function(response) {
            // parse response here

            return response;
        };

        $http.defaults.transformResponse = [parseResponse];
    }
]);

This will override the default behavior, you can also set it as an empty array if only selected responses need to be transformed.

See this question/answer: AngularJS, $http and transformResponse

Community
  • 1
  • 1
KungWaz
  • 1,918
  • 3
  • 36
  • 61
1

You should use

$http.defaults.transformResponse

You also don't wanna use .push(). You need your transformer to do its thing before angular's default transformers. You should use .unshift() instead.

So your code should be

$http.defaults.transformResponse.unshift(transformResponse);

where transformResponse is a function which will transform the response from the server into a proper JSON.

Tom Teman
  • 1,975
  • 3
  • 28
  • 43