Search code examples
javascriptjsonangularjsangular-httpangular-http-interceptors

Angular 1.3.0 honors JSON responses, how do I override this or pre-parse the response before Angular?


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

Solution

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