how to get headers from response in angularjs - angularjs

This is my sample, i'm not get response headers, it returns undefined
I'm trying to get custom response headers like reponse.header['X-auth-token'] but it returns undefined
I'm new to angular js, Please share your idea
Thanks in advance
//I'm trying to get custom response headers here (using alert(response.headers);)
Controller
UIAppRoute.controller('test', ['$scope', 'checkStatus', function($scope, checkStatus) {
$scope.data = {};
checkStatus.query(function(response) {
alert(response.headers);
angular.forEach(response, function (item) {
alert("resp2"+ item);
});
$scope.data.resp = response;
});
}]);
// sending request to server
service
-------
UIAppResource.factory('checkStatus', function($resource){
var auth = Base64.encode("abcde:abcde");
return $resource(baseURL + "status", {},
{
'query': {
method: 'GET',
headers: {
'Accept':'application/json',
'Content-Type':'application/json',
'Authorization': 'Basic '+ auth,
'Access-Control-Allow-Headers' : 'Origin, X-Requested-With, Content-Type, Accept'
},
isArray: false
}
}
)
how to get headers from response in angularjs ?
Please share your idea
Thanks in advance

response.headers is a function an not a map, so you have to call it instead of accessing it via a key.
response.headers('headerName') should give you the respective header.
See also http://code.angularjs.org/1.2.16/docs/api/ng/service/$http
For $resource see http://code.angularjs.org/1.2.16/docs/api/ngResource/service/$resource
var User = $resource('/user/:userId', {userId:'#id'});
User.get({userId:123}, function(u, headers){
alert(headers('X-Internal-Auth-Token'))
});
});

the first param of function is the returned data, the second param is headers;
so you should write as follow:
checkStatus.query(function(data,headers) {
console.log(headers('xxxx'));
});

Related

$http get dosn't work frome code but works with other rest client

I have a problem with angular $http get with Authorization header.
I tried to excute the same request with different rest client and response are the same each one.
Advanced Rest Client Chrome extension
Soap-Ui
Insomnia
I have always received the same response with 200 status code.
but when I try to make the same call from my angular application I get 403 status code and response is an OPTIONS.
where I'm wrong?
this is my code:
Config
app.config(function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.headers.common['Authorization']='Bearer 24ac24e6-0f9b-48b5-923f-b75986226bd9';
});
Service
app.service('DiscoveryService', function ($http) {
this.getData = function (callbackFunc) {
$http({
url: 'https://test.test/test-api/source-monitor/v1/discover',
method: 'GET',
headers: {
"Content-Type": "application/json"
}
}).success(function (response) {
console.log(response);
}).error(function (error) {
console.log(response);
});
};
});
Controller
DiscoveryService.getData(function (dataResponse) {
$scope.data = dataResponse;
});

how to pass headers in http call in angularjs

I am developing mobile application in cordova/phonegap. I am using angularJS for front-end. I am calling services which required 'API-KEY' attribute as header in post request.
I show some documentations, and tried with those way. but not worked.
postServiceDataWithHeader: function (url, data) {
var deferred = $q.defer();
var req = {
method: 'POST',
url: url,
data: JSON.stringify(data),
headers: {
'user-Token': $rootScope.user.APIKEY,
'content-Type': 'Application/Json'
}
}
$http(req).success(function (data) {
deferred.resolve(data);
}).error(function (data, status, headers, config) {
alert("Server failed to save data");
deferred.reject(status);
});
return deferred.promise;
}
I tried to add headers in call with,
JodoModule.config(function ($routeProvider, $httpProvider) {
$httpProvider.defaults.headers.post['user-Token'] = 'finding???';
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
});
and second approach was,
JodoModule.run(['$rootScope', '$http', function ($rootScope, $http) {
$http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w';
}]);
I am able to call services, but on server side, I am not getting header values, even in fiddler also headers are not passed.
What is the reason ? Do I need to add anything else in code for passing headers for each POST request. ?
I've made working plunker for you using one of yours approach
http://plnkr.co/edit/36Dq6UXgyeMEXOzycrua?p=preview
app.config(function ( $httpProvider) {
$httpProvider.defaults.headers.post['User-Token'] = 'finding???';
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
});
Although if it's CORS you have to add 'User-Token' to accepted headers
i.e. for apache2
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "origin, user-token, x-requested-with, content-type"
Header set Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

$http Post to php backend, but the server side gets nothing

I'm learning AngularJS, and trying to post dump data to the php backend using the coding below.
angular.module('app.customerModule', [])
.factory('customerFactory', function($scope, $http) {
return {
var customer = {customer: '1234'};
httpNewCustomer: function(callback) {
$http.post('http://domain.local/customer_new.php', )
.success(function(data) {
})
}
}
})
.controller('customerController', function($rootScope, $scope, customerFactory) {
$scope.newCustomer = function() {
customerFactory.httpNewCustomer(function(dataResponse) {
});
}
});
Unfortunately at the server side gets nothing for $_POST;
This is what the http header looks like.
I also tried with this alternative coding
httpNewCustomers: function(callback) {
var postData = {customer: '2345'};
$http({
method: 'POST',
url: 'http://domain.local/customer_new.php',
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'}
})
.success(function(data) {
})
}
This is what the http header looks like.
When I tried with jQuery using this coding, everything is just fine.
var postData = {customer: '3456'};
$.ajax({
type: 'POST',
url: 'http://domain.local/customer_new.php',
dataType: 'json',
data: postData,
success: function(data) {
// console.log(data);
}
});
Please help me config the $http to post the data to the php backend.
angular by default only supports a json request transformer. as you can see, both your angular requests have data, but they are json. You either need to change the server so it can parse json, or add a request transformer so the data is in form-encoded format.
You can read more about $http transformers here: https://docs.angularjs.org/api/ng/service/$http

Pass argument from controller to service in angularjs

I'm facing the problem on passing the argument from controller to service module
I don't know where I have pass the arguments in controller module and how to get the value in service module. here is my code,
Controller module
var user = $scope.username;
var pass = $scope.password;
*// how to pass the username and password here*
checkStatus.query(function(response, headers) {
alert(headers('X-Internal-Auth-Toketn'));
});
Service module
UIAppResource.factory('checkStatus', function($resource) {
var auth = Base64.encode("abcd:abcd"); // *I need username and password here*
return $resource(baseURL + "status", {},
{
'query': {
method: 'GET',
headers: {
'Accept':'application/json',
'Content-Type':'application/json',
'Authorization': 'Basic '+ auth,
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'
},
isArray: false
}
}
)
});
I'm new for angularjs, please help me to solve this problem
Thanks in advance
Rather than return $resource, return an object that contains functions that use the $resource internally. Eg:
Controller:
var user = $scope.username;
var pass = $scope.password;
checkStatus.customQuery(user, pass, function(response, headers) {
alert(headers('X-Internal-Auth-Toketn'));
});
Service:
UIAppResource.factory('checkStatus', function($resource) {
return {
customQuery: function(user, pass, callback) {
var auth = Base64.encode(user + ':' + pass);
var myRes = $resource(baseURL + "status", {}, {
'query': {
method: 'GET',
headers: {
'Accept':'application/json',
'Content-Type':'application/json',
'Authorization': 'Basic '+ auth,
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'
},
isArray: false
}
});
myRes.query(callback);
}
};
});
Obviously this will create a new $resource for every customQuery() call, so it is most likely better to store the created $resource inside the service once. To do this I would create an initialiser function which the username/password can be passed to.
You should restructure your factory definition that makes easier for your to pass parameters. CheckStatus should be a method on the object returned from factory The definition should look something like
UIAppResource.factory('authService', function($resource) {
var service={};
service.checkStatus=function(userName,passWord) {
var auth = Base64.encode("abcd:abcd"); // *I need username and password here*
return $resource(baseURL + "status", {},
{
'query': {
method: 'GET',
headers: {
'Accept':'application/json',
'Content-Type':'application/json',
'Authorization': 'Basic '+ auth,
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'
},
isArray: false
}
}
)
}
return service;
});
In you controller then you call
authService.checkStatus($scope.userName,$scope.password);

AngularJS withCredentials

I've been working on an AngularJS project which has to send AJAX calls to an restfull webservice. This webservice is on another domain so I had to enable cors on the server. I did this by setting these headers:
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Origin", "http://localhost:8000");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Credentials", "true");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
cresp.getHttpHeaders().putSingle("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
I'm able to send AJAX requests from AngularJS to the backend but I'm facing a problem when I try to get an attribute of a session. I believe this is because the sessionid cookie doesn't get send to the backend.
I was able to fix this in jQuery by setting withCredentials to true.
$("#login").click(function() {
$.ajax({
url: "http://localhost:8080/api/login",
data : '{"identifier" : "admin", "password" : "admin"}',
contentType : 'application/json',
type : 'POST',
xhrFields: {
withCredentials: true
},
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
})
});
$("#check").click(function() {
$.ajax({
url: "http://localhost:8080/api/ping",
method: "GET",
xhrFields: {
withCredentials: true
},
success: function(data) {
console.log(data);
}
})
});
The problem that I'm facing is that I can't get this to work in AngularJS with the $http service. I tried it like this:
$http.post("http://localhost:8080/api/login", $scope.credentials, {withCredentials : true}).
success(function(data) {
$location.path('/');
console.log(data);
}).
error(function(data, error) {
console.log(error);
});
Can anyone tell me what I'm doing wrong?
You should pass a configuration object, like so
$http.post(url, {withCredentials: true, ...})
or in older versions:
$http({withCredentials: true, ...}).post(...)
See also your other question.
In your app config function add this :
$httpProvider.defaults.withCredentials = true;
It will append this header for all your requests.
Dont forget to inject $httpProvider
EDIT : 2015-07-29
Here is another solution :
HttpIntercepter can be used for adding common headers as well as common parameters.
Add this in your config :
$httpProvider.interceptors.push('UtimfHttpIntercepter');
and create factory with name UtimfHttpIntercepter
angular.module('utimf.services', [])
.factory('UtimfHttpIntercepter', UtimfHttpIntercepter)
UtimfHttpIntercepter.$inject = ['$q'];
function UtimfHttpIntercepter($q) {
var authFactory = {};
var _request = function (config) {
config.headers = config.headers || {}; // change/add hearders
config.data = config.data || {}; // change/add post data
config.params = config.params || {}; //change/add querystring params
return config || $q.when(config);
}
var _requestError = function (rejection) {
// handle if there is a request error
return $q.reject(rejection);
}
var _response = function(response){
// handle your response
return response || $q.when(response);
}
var _responseError = function (rejection) {
// handle if there is a request error
return $q.reject(rejection);
}
authFactory.request = _request;
authFactory.requestError = _requestError;
authFactory.response = _response;
authFactory.responseError = _responseError;
return authFactory;
}
Clarification:
$http.post(url, {withCredentials: true, ...})
should be
$http.post(url, data, {withCredentials: true, ...})
as per https://docs.angularjs.org/api/ng/service/$http

Resources