$http post response errors with 302 status - angularjs

The return of the post is falling through the error callback yet the json I'm expecting is being returned by the api call. It is visible when I console.log the error object. I'll post the error log after the code.
The payload (userCreds) is json. Using postman, the api call returns as expected
Here's the post call:
var deferred = $q.defer();
$http.post(url, userCreds)
.then(function(data, status) {
$log.info('validateLogin status: ' + status)
if(data){
requestor = data;
}
deferred.resolve(requestor);
}, function (data, status) {
var error = data || "Request failed";
$log.error('validateLogin error: ' + JSON.stringify(error));
deferred.reject(error);
});
return deferred.promise;
The error object has the correct response in it with a 302 status. I noticed the transformRequest and transformResponse were null. I don't recall having to define these in the past. I thought angular automatically dealt with strings and javascript objects during transformations.
{"data":{"$id":"1","innCodes":[],"userTypeId":0,"formId":0,"onqUserId":null,"fullName":"User Smith","firstName":"User","lastName":"Smith","phone":"214-555-4450","email":"user#email.com","userId":null,"password":null,"title":"Project Manager","fax":null,"mobile":null,"role":null},"status":302,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"url":"http://localhost:25396/api/user/ValidateCredentials/","data":{"userName":"userid1234","password":"pwd123456"},"headers":{"Accept":"application/json, text/plain, */*","Content-Type":"application/json;charset=utf-8"}},"statusText":"Found"}

Ended up being the valid api response 302 (found) that was causing the quirky behavior. I was able to get the status code changed to 200 (OK) and now everything is working as expected. The 302 status was causing angular to reject the promise.
This line of code in angular v 1.2.26
return (isSuccess(response.status))
? resp
: $q.reject(resp);

Related

Response is undefined in success $http call angularJS

Although my backend is working correctly and I'm getting correct response from Postman crafted request
I can't see response in my angularJS controller. ( i execute this call inside controller to simplify situation )
$scope.click = function (auction_id) {
$http({
url: baseUrl + 'auctions/' + auction_id +'/followers',
headers: {
'Content-Type' : 'application/vnd.api+json'
},
method: 'POST'
})
.then(function(response) {
console.log(response);
})
.catch(function(response) {
return response;
});
};
I'm passing token with httpInterceptor which is working fine for the rest of my app.
URL is correct because I'm getting valid error number in console:
POST ##################/v1/auctions/172/followers
422 (Unprocessable Entity)
CategoryCtrl.js:64 undefined
64 line is that one console log in success .then(function....
Headers in (which I believe is) response headers from postman tab (third from Body in first screenshot)
Why response is undefined?
*Hashes in url code are mine.
From your REST API request, you're getting response with status 422, that means you've got a client error. Regarding your request, you have to handle a request when error will come. To handle error in asynchronous requests there is a second parameter of .then(mySuccessMethod(), myMethodOnError()) method.
More details about .then() and .catch() methods for promisses.
$scope.click = function (auction_id) {
$http({
url: baseUrl + 'auctions/' + auction_id +'/followers',
headers: {
'Content-Type' : 'application/vnd.api+json'
},
method: 'POST'
})
.then(function(response) {
console.log(response);
}, function(error) {
// Here goes your code to handle an error with status 4XX
console.log(error)
})
.catch(function(response) {
// Catch will come when you throw an error
return response;
});
};
When you made the request in Postman, you pass the token in the Auth attribute of the header in the request. In your code, you did not.

Why am I unable to get error.status and error.statusText from Angular $http.get. error response?

I have a function that looks like this in an angular controller:
$http.get(dataUrl)
.then(function (response) { // success getProducts
$scope.data.products = response.data;
})
.catch(function (error) {
$scope.data.error = error;
});
dataUrl is a constant and when correct returns a list of products and everything works.
Next I wanted to test the error handling.
So I changed the dataUrl to an incorrect port number to get my data.
Now my error div shows and my content div hides.
This is correct functionality.
Here is my problem.
In my div when I show error.status, it comes back as -1. The example I am following says it should be 404. Also my statusText is empty or "".
Why is my error object not populating with anything.
I originally had this set up with error function as the second callback to then().
But I get the same results either way and I think catch() is cleaner as eluded to in another posted question on stack.
From https://docs.angularjs.org/api/ng/service/$http
A response status code between 200 and 299 is considered a success
status and will result in the success callback being called. Any
response status code outside of that range is considered an error
status and will result in the error callback being called. Also,
status codes less than -1 are normalized to zero. -1 usually means the
request was aborted, e.g. using a config.timeout. Note that if the
response is a redirect, XMLHttpRequest will transparently follow it,
meaning that the outcome (success or error) will be determined by the
final response status code.
The correct URL is: "http://localhost:5125/products" (as in:
angular.module("sportsStore")
.constant("dataUrl", "http://localhost:5125/products1")
.controller("sportsStoreCtrl", function ($scope, $http, dataUrl) {
$scope.data = {};
$http.get(dataUrl)
.then(function (response) { // success getProducts
$scope.data.products = response.data;
})
.catch(function (error) {
$scope.data.error = error;
});
});
If I change it to: "http://localhost:5000/products", the ajax request is no longer going to a webserver because it cannot find deployd serving up the products collection on port 5000. So the comment from JB Nizet is correct above.
There is no server to send back 404 or 500 so the default status must be -1 and the default statusText must be "".
But if I try this: http://localhost:5125/products1, then the ajax request finds deployd, but sends back 404 because there is no products1 collection or products1 API and so no get method for a products1 collection. So deployd sends back 404 in this case:

Why does a POST response of 204 (no content) trigger the Angularjs error function?

I have an Angularjs application that uses $http.post() to make web service calls. The method it calls has a void return type, and it generates a 204 (no content) response code. This goes into the error function that is defined in the .then() callback, and prints "no element found" in the log.
If I return anything from the method, it returns the normal 200 response code.
Why is a success code triggering the error function?
Code as requested:
function myFn(inputData) {
var d = { data: inputData };
$http.post("../api/my/serverFn", d)
.then(
function(response) {
$rootScope.AddMsg("Success");
},
function(response) {
// The 204 response goes here.
$rootScope.AddMsg("Error");
});
}
The requested screenshot:
AngularJS doesn't natively consider a 204 response as an error. The investigation revealed that there was in fact an http interceptor in the stack that rejected the promise if the response received had a 204 status, turning the successful response into an error.

$http.post returns status code 0 even if post is created in database

I am using angular, and in my controller I want to save my order. I use $http and the code looks like this:
$http({method: "post", url:$scope.saveOrderUrl}
).success(function (data) {
$scope.order = data;
}).error(function (data, status) {
alert("Error when saving order. Status: " + status);
});
The order is created in the database, but http.post is returning an error with status code 0. The error alert appears before the api controller has been able to return a success response back to the view.
Am I doing something wrong? What is it that determines if http returns a success or an erro when it doesn't wait for the server?
try again with code below:
$http.post(url).success(function(data){
$scope.order = data;
}).error(function(msg){
alert(msg);
});

How to get data from JSONP error callback in angularjs?

I am trying to get response message from jsonp error callback in angularjs, but response data is undefined. I return the response with 409 http code. If to open jsonp url directly in browser it shows "angular.callbacks._0({"message":"Reset link is incorrect"})", but I can't get this message in error callback. What am I doing wrong?
// Extend angular app for api requests
app.factory('User', function($http) {
var User = function(data) {
angular.extend(this, data);
};
// Send link for password reset to entered email
User.reset_password = function() {
return $http.jsonp(jsonp_url + 'user/reset_pass?_method=post&user_key=' + user_key + '&callback=JSON_CALLBACK');
};
return User;
});
app.controller('ResetPasswordController', function ResetPasswordController($scope, User){
$scope.submit = function() {
var response = User.reset_password();
response.then(function(data){
//Success callback
}, function(data){
// Error callback
console.log(data) // Output: {config : {...}, data: undefined}
});
}
});
As said Brandon Tilley it is not possible to get data from jsonp response with http error code. If you want anyways to get error message you need to send something like this {result: false, msg: 'Error occured...'} with "good" http code, for example 200.

Resources