How to handle plain text server response? How to handle plain text server response? angularjs angularjs

How to handle plain text server response?


$resource is a convenience wrapper for working with Restful objects. It'll automatically try to parse as JSON and populate the object based on the $resource definition.

You are much better off using the $http service for non restful resources.

This is a lower level API that doesn't have such overbearing object mapping.

e.g.

$http({method: "GET", url: "/myTextDocURL"})  .success(function(data){       // data should be text string here (only if the server response is text/plain)  });


According to the documentation you specify a custom action for a resource that can override the default behaviour which is to to convert the response from json to a javascript object. The 'data' param of the transformResponse function will contain your text payload.

In this case the transformResponse method returns an object containing the string rather than just the string itself because otherwise it would STILL try to convert the string to an array.

    var Stub = $resource('/files/:filename', {}, {'getText': {        transformResponse: function(data, headersGetter, status) {            return {content: data};        }    }});

To use the resource call your custom getText() action rather than plain old get():

    Stub.getText({'filename': 'someFile.txt'}, function(response) {        console.info("Content of someFile.txt = " . response.content);    });

This is an old post but I figured it deserved an new answer.