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.
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.
returned data should look like this:
{ "status": "success", "path": "assets/profile/profilepicture.png" }
note " must be instead of '
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With