Krzysztof Morcinek
Krzysztof Morcinek

Reputation: 1021

AngularJS treats POST response as string array instead of just string

I am making a POST request:

var offers = $resource('/api/offers/:id', { 
    id: '@id' 
}

offers.save({}, { name: $scope.newOfferName }, function (offerId) {
    $location.path('/offers/' + offerId);
});

I expect offerId to be a string "key", but instead I get an array [0] "k", [1] "e", [2] "y".

On the backend I use Nancy and I return the response using:

Post["/"] = _ =>
{
    return Response.AsText("key");
};

The response Header say Content-Type:text/plain and in Chrome preview (Network tab) I can see "key".

When I return an object as JSON it's working fine, but I don't want to create fake class (having a string field) just to pass a string to the client.

I assume Nancy is fine here. What is happening with Angular?

Upvotes: 0

Views: 1191

Answers (2)

Christian Horsdal
Christian Horsdal

Reputation: 4932

You don't have to create a class for that. You can use an anonymous type:

Post["/"] = _ =>
{
    return Response.AsJson(new { offerId = "key" });
};

Upvotes: 2

Zerot
Zerot

Reputation: 196

angular has a default transform that tries to parse incoming data as json. https://github.com/angular/angular.js/blob/master/src/ng/http.js#L94

You could remove that transform from the transformers array in $http completely, or replace it with one that checks the content-type before trying to transform the data.

Upvotes: 1

Related Questions