Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 381
claydiffrient Avatar asked Apr 14 '14 18:04

claydiffrient


3 Answers

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.

like image 67
claydiffrient Avatar answered Nov 13 '22 06:11

claydiffrient


returned data should look like this:

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

note " must be instead of '

like image 30
karaxuna Avatar answered Nov 13 '22 06:11

karaxuna


In my case, the server was returning a "File Not Found" string, while the native $http in Angular was expecting a response of type "application/json". So even though the status code was 200 OK, it was entering the .error part of the http method.

To fix this, I had to return a JSON Object from the server.

like image 1
Edwin Samuel Jonathan Avatar answered Nov 13 '22 05:11

Edwin Samuel Jonathan