How to handle plain text server response?

All we need is an easy explanation of the problem, so here it is.

I am new to AngularJS, and building an app that will interact with a server. The server has a REST API, but responds to some methods with plain text, and to others with JSON. I have implemented a simple http request method using AngularJS’ $resource service.

However, when the server response is plain text, the response in AngularJS is an object with one entry for each character in the response word. How can I get around this (in a good way)? Ideally, I would like to be able to tell my service when to expect plain text and when to expect JSON, and get a nicely formatted response in both cases.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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

Method 2

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.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply