How can I stop Angular $http from deserializing the response body? - angularjs

This:
$http({method: 'GET', url: '/some/url/returning/json').
success(function(data, status, headers, config) {
console.log(data);
});
shows that Angular is giving me a JavaScript object as the first argument to my success handler. Presumably, it is trying to be smart by sniffing the content-type of the response.
This is undesired behavior. How do I tell Angular to give me the response body as a string?

The undesired behavior is caused by Angular's transformResponse. To turn this off, do:
$http({method: 'GET', url: '/some/url/returning/json', transformResponse: [] }).
success(function(data, status, headers, config) {
console.log(data);
});

It mentions in the docs that the responseType config option can be used, presumably as:
$http({method: 'GET', url: '/some/url/returning/json', responseType: 'text'})...

Related

Angular $http is not sending data

I know it has been solved here many times, but I'm still not able to get it working.
My js call is:
var data = { value: 7 };
$http.post('api/controller/method', data);
But in fiddler there is no Content-Type and no JSON data.
I want the Content-Type to be 'application/json' which should be default, right?
Thanks
var data = { value: 7 };
$http({
url: "api/controller/method",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param(data)
}).success(function(data, status, headers, config) {
//some code when success post
}).error(function(data, status, headers, config) {
//some code when error post
});
Try this:
var response = $http.post('api/controller/method', data);
response.success(function(data, status1, headers, config) {
//
}

store response header value during angular http post

I am making an angular http post to an API which like this
$http({
method: 'POST',
url: 'http://api/ClientEndpoint',
data: register,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
transformRequest: function (obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
}).error(function (data, status, headers, config) {
alert(data);
});
which is returning the following response
But I am not able to store the response path in a variable. How can I do that?
It is cross domain scenario and this is the response being showed in chrome console
I want to access store the ClientEndpoint value
Did you forget the .success(function (data) { }) callback ? just like the .error() you put after the http() function
i hope this will solve your problem ;)
Use the headers variable in either your .succes(response, headers) or .error(response, headers).
E.g :
.success(function(data, status, headers, config) {
//Success Handling
});
.error(function(data, status, headers, config) {
//Error Handeling
});
This only works if you are on the same domain as the server, if it's cross domain, the server has to send the Access-Control-Expose-Headers for you to make this work.

Why variable is not decremented?

In Angular JS controller there is variable:
$scope.currentCount = {
'subscribers' : 0
}
Also in HTML template:
<span>{{currentCount.subscribers}}</span>
When I call method in this controller, this variable is not decremented in template, why?
$scope.saveSubscriber = function (type, name) {
$scope.saveSubObj.type = type;
$http({
url: "/subscribe",
method: "POST",
data: $.param($scope.saveSubObj),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data, status, headers, config) {
$scope.currentCount.subscribers--;
}).error(function(data, status, headers, config) {
//TODO
});
}
Look at success AJAX response:
$scope.currentCount.subscribers--;
Are you sure it fired the success method? I just checked and got the correct result in my local testing.
Could you please put $scope.currentCount.subscribers--; inside the $http error() method as well? Let's check then whether it decreases or not.

$http - null plain text response

I have an $http POST call in AngularJS that won't show the server response if the request was bad.
myFactory.create = function(formData) {
deferred = $q.defer()
$http({method: 'POST', url: url, responseType: 'json', data: formData})
.then(function(data) {
deferred.resolve(data);
}, function(response, status, headers, config) {
deferred.reject(response);
});
return deferred.promise;
};
When I submit incorrect data, the API responds with a 400 - Bad Request. If I look at the response in Chrome Developer tools, there is a plain text message: "Vertical is not correct." However, that message is not in the response on the $http error callback.
I can get everything else (status, headers and config) but my response data is null.
Successful POSTs are processed correctly so I know that the function generally works.
Any idea why I would be able to see the response in Chrome but not able to access it via $http?
You can refactor to this:
myFactory.create = function(formData) {
var url = 'api/create';
return $http({
method: 'POST',
url: url,
responseType: 'json', //Are you sure that it is returning a json??
data: formData
});
};
Then check the return of the promise like this wherever you wish to call it,
myFactory.create().then(
function(data){
console.dir(data);
},function(response, status, headers, config) {
console.dir(response);
});
This should work and you should see the data on the logs.

how to redirect with angularjs

I have server side code which sends a response back (expressjs) to state if the user is authenticated or not.
I use $http post request and get the success back if all is ok. If user is authenticated I need to redirect the user to the relevant page.
My code here currently does not work or throw an error either when using debugging tools
$http({ method: 'POST',
url: '/login',
data: JSON.stringify({'username' : $scope.user.username, 'password' : $scope.user.password }),
headers: {'Content-Type': 'application/json'}}).
success(function (data, status, headers, config) {
$scope.invalid = false;
$window.location.href = '#/admin/';
}).
error(function (data, status, headers, config) {
console.log(status);
$scope.list = data;
});
return;
};
Any help would be great.
You can use $location to redirect
$location.path( "#/admin/" );
I would have expected your $window.location to also perform the redirect, so there could be something else going on. Do you have a route for '#/admin/' set up in a routeProvider? If not the default route would execute, if specified.

Resources