Response is undefined in success $http call angularJS - 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.

Related

CORS post call not working in Angularjs

I am trying to implement cross-origin post call from angularjs application, then I get the following error.
Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
But, when I make a Ajax call it works properly.
How HTTP post call work in angularjs?
Ajax call
$.ajax({
type: 'POST',
url: getAccessTokenUrl,
data: JSON.stringify(clintdata),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(resultData) {
console.log(resultData);
},
error: function (request, status, error) {
console.log(status);
}
});
Angularjs HTTP call
$http({
method: 'POST',
url: getAccessTokenUrl,
data: clientdata,
headers: {
'Authorization': undefined,
'Auth-Token': undefined
}
}).then(function(res){
console.log(res);
}, function(err){
console.log(err);
});
I have some default setting. Authorization is for others REST
$http.defaults.headers.common['Content-Type'] = 'application/json;charset=utf-8;' ;
$http.defaults.headers.common['Auth-Token'] = 'X-Requested-With';
$http.defaults.headers.common['Authorization'] = $('#Authorization').val();
Access-Control-* headers are response headers. They come from the server in response to a request. You do not apply them to your request headers.
If your jQuery request works correctly without adding any additional headers, then your AngularJS request should work the same.
The equivalent jQuery request in AngularJS (including removing the Authorization and Auth-Token headers you've set via defaults) is
$http.post(getAccessTokenUrl, clientdata, {
headers: {
Authorization: undefined,
'Auth-Token': undefined
}
}).then(response => {
console.log(response.data)
})
or the long version
$http({
method: 'POST',
url: getAccessTokenUrl,
data: clientdata,
headers: {
Authorization: undefined,
'Auth-Token': undefined
}
}).then(...)
AngularJS by default...
POSTS requests as application/json content-type
Serializes the data property to JSON
Expects a JSON response
Resolves the $http promise with a response object with the response body parsed as JSON into the data property
Remove the following setting
$http.defaults.headers.common['Auth-Token'] = 'X-Requested-With';
$http.defaults.headers.common['Authorization'] = $('#Authorization').val();
Add Authorization header dynamically from Interceptor
request: function(config) {
if (angular.isUndefined(config.skipInterceptor) || !config.skipInterceptor) {
// add Authorization token
}
return config;
}
Http call like this
$http.post('your url', {
skipInterceptor: true
})

chrome is not responding for API response

I have one api which is being called from Angularjs from front end, when API hit from post-man it is taking hardly 1 sec to send response, but when it is being called from chrome browser, it leads to hangs it up and Aw, Snap! page.
we are using remote desktop, upon which only chrome is running with a single tab.
Any thoughts we this is happing to us, since api is fine with postman returning a response within 1 sec.
Sample Code of Angular service method, which send the response to controller,
this.getData() = function(chartJson) {
return $http({
method: "POST",
url: "api/xxxxxxxx/xxxxxxxx",
headers: { 'Content-Type': "Application/json" },
data: chartJson
});
};
In controller, we access this above method like,
this.getData()
.then(function(response){
console.log(response);
}, function(error){
console.log('Error '+error);
});
Thanks in advance.

Creating custom header for $http in AngularJs

In my controller i want send a request using get method if $http, in that get method i want to send the sessionID in headers. Below am giving the code snippet please check.
this.surveyList = function () {
//return session;
return $http.get('http://op.1pt.mobi/V3.0/api/Survey/Surveys', {headers: { 'sessionID': $scope.sessionid}})
.then(function(response){
return response.data;
}, function(error){
return error;
});
}
but this is not working when i send this vale in backend they getting null.
So how to resolve this.
we have a issue where the api is getting called twice from angular , however it works only once when called with the POSTMAN. And here with the custom header passed to the api, the action is called twice. What could be the reason for it?
Try in this way,
$http({
method: 'GET',
url: 'http://op.1pt.mobi/V3.0/api/Survey/Surveys',
headers: {
'sessionId': $scope.sessionid
}
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs,
// or server returns response with an error status.
});

angular laravel nginx 400 Bad Request

Help, I've got 400 error on POST and or PUT method, but GET works just fine,
I'm using angular as front end and laravel as API, my server is using nginx,
I've used CORS and I everything works fine on my local vagrant which is running on apache.
I'm sure I have my route set correctly, here's some of it from the module I use:
Route::group(array('prefix'=>'/api', 'middleware' => 'cors'),function(){
Route::post('/create_level', 'LevelController#store');
Route::get('/read_level', 'LevelController#index');
Route::get('/read_level/{id}', 'LevelController#show');
Route::put('/read_level/{id}', 'LevelController#update');
Route::delete('/read_level/{id}', 'LevelController#destroy');
here's part of my angular service:
app.service("edulevelService", function ($http, $q, $rootScope)
{
edu.updateEdulevel = function(id, edu){
var deferred = $q.defer();
$http.put($rootScope.endPoint + 'read_level/'+ id, edu)
.success(function(res)
{
deferred.resolve(res);
})
.error(function(err, stat){
deferred.reject(err);
console.log('error code: Ser-UEDU');
});
return deferred.promise;
}
edu.createEdulevel = function(edu){
var deferred = $q.defer();
$http.post($rootScope.endPoint + 'create_level', edu)
.success(function(res)
{
deferred.resolve(res);
})
.error(function(err, stat){
deferred.reject(err);
console.log('error code: Ser-CEDU');
});
return deferred.promise;
}
....
oh I forgot to mention different method cause different error code POST cause 405, PUT cause 400, and I've tried using Postman:
POST is working using text type and return 405 using application/json,
but when I tried
PUT method even though it return 200 I only got NULL data entered to my db (text type), and if I use application/json it return 400
Please Help
Finally found solution:
change $http.post to:
$http({
method: "post",
url: $rootScope.endPoint + 'create_level',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({ .... })
})
somehow it works, exept on my login page which using stellizer to do post method and i can't find how should I change it without breaking all the function...
any one?
I only need to add:
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
and
data: $.param({ ...... })

Angular - How to properly handle an HTTP error from server?

Currently I've got this:
$http({
method: 'POST',
url: 'http://api-endpoint/somescript/',
data: formData,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function (response) {
console.log(response);
});
If the script on the other end works out ok, then gets called. However, let's say the script on the server end has some sort of error that's not properly caught. If I make up an error by tossing in some garbage call like asdfasdf(), the then function isn't called, and instead I get this in the browser console:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://api-endpoint/somescript/. (Reason: CORS
header 'Access-Control-Allow-Origin' missing).
How do I catch this in the Angular code so I can handle it in a user-friendly manner?
EDIT: This is not a duplicate, as it is specific to Angular.
The $q.then() method accepts three function parameters, the first being the handler for a successful callbacks, the second being for errors, and the third being for notify. $http leverages $q behind the scenes so this thenable should behave like the documentation suggests.
To handle errors in the above code, just toss in an additional function for error handling as such:
.then(function (response) {
console.log(response);
}, function(response) {
console.log(response);
});
Feel free to browse the $q documentation, specifically The Promise API, for additional details.
To handle this, we will have to add a service/factory to intercept http calls. You can do it like this in your config
$httpProvider.interceptors.push('httpRequestInterceptor');
Now, the above service will be something like this
angular.module("app").factory('httpRequestInterceptor', function ($q) {
return {
'request': function (config) {
// Extract request information
return config || $q.when(config);
},
'responseError': function(rejection) {
// Extract response error information and handle errors
return $q.reject(rejection);
}
}
});

Resources