claydiffrient claydiffrient - 1 month ago 20
AngularJS Question

Angular $http calls error on 200 response

I have this code used within an Angular service:

var formData = function (data) {
var fd = new FormData();
angular.forEach(data, function (value, key) {
fd.append(key, value);
});
return fd;
}

var updateUserPic = function (profilePic, callback, userId) {
var userId = userId || FRAME_API.proxyUserId; // jshint ignore:line
if (!_.isFunction(callback)) {
throw new Error('You must provide a callback function.');
}
$http({
method: 'POST',
url: '/Learn/PostUserProfile.ashx?action=profilepic&userid=' + userId,
data: {up_picfile: profilePic},
transformRequest: formData,
headers: { 'Content-Type': undefined}
}).success(function (data, status, headers, config){
callback([data, status, headers, config]);
return;
}).error(function (data, status){
console.log([status,data]);
callback(false);
return;
});
};


Inspecting using the Network tab in Chrome's Developer Tools shows that there is a
200 OK
response. Also the data goes through as expected. However, the problem is that the
error
callback is the only one ever called regardless of the fact that it has a status of 200. Also the
data
and
status
parameters come in as
undefined
.

Any reason this would be the case?

The response from the server is this:

{status: 'success', path: 'assets/profile/profilepicture.png'}


Also, note that this response cannot be changed by me. It is coming from a vendor's script running on the server which I cannot access.

Answer

I used a custom response transformer to turn it to valid JSON:

var responseTransformer = function (data) {

   return data.replace('status', '"status"')
              .replace('\'success\'', '"success"')
              .replace('path', '"path"')
              .replace('\'assets/profile/profilepicture.png\'',
                       '"assets/profile/profilepicture.png"');

};

This made it work just fine.