AngularJS basic auth - angularjs

Why do i get a 401 with this? The credentials are correct.
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
$httpProvider.defaults.headers.common.Authorization = 'Basic ' + btoa("xxx:yyy");
$httpProvider.defaults.headers.common.withCredentials = true;
}
....
$http({
method: "POST",
url: url
data: data,
})

Try including your Authorization header inside $http like:
$http({
method: "POST",
url: url
data: data,
headers: {'Authorization': 'Basic ' + btoa("xxx:yyy")},
})

Related

AngularJS 406 not acceptable http post request

I have a problem with a Post query that I use for a form. I get a "406 not acceptable" error every time I try to validate my form, and Object.data is blank..
var edit = function(form){
var token = window.localStorage.getItem('token');
$ionicLoading.show();
return $http({
method : 'POST',
url : API.url + '/user',
headers : {Authorization : 'Bearer ' + token},
transformRequest: function(data, headers){
console.log(headers);
headers = angular.extend({}, headers, {'Content-Type': 'application/json;charset=UTF-8'});
console.log(headers);
console.log(data);
console.log(angular.toJson(data));
return angular.toJson(data); // this will go in the body request
},
data : form
}).then(function(result) {
console.dir(result.data);
},function errorCallback(response) {
console.log(response);
});
};
I I do not understand why it does not accept..
You should to send a json data to your server
try this following code by adding 'Accept': 'application/json, */*' to your header:
var edit = function(form){
var token = window.localStorage.getItem('token');
$ionicLoading.show();
return $http({
method : 'POST',
url : API.url + '/user',
headers : {
Authorization : 'Bearer ' + token,
'Accept': 'application/json, */*'
},
transformRequest: function(data, headers){
console.log(headers);
headers = angular.extend({}, headers, {'Content-Type': 'application/json;charset=UTF-8'});
console.log(headers);
console.log(data);
console.log(angular.toJson(data));
return angular.toJson(data); // this will go in the body request
},
data : form
}).then(function(result) {
console.dir(result.data);
},function errorCallback(response) {
console.log(response);
});

in AngularJS, JWT Authorization header is undefined

I am trying to access an api using jwt. When I post with credentials, I get the id_token from server. I extract it, but when I try to add the token to the next requests in Authorization header using Bearer, the token is shown as undefined, therefor receiving the 500 Internal Error as "JWT strings must contain exactly 2 period characters. Found: 0". The console error is shown in the picture
My code is as following:
angular.module('myApp', []).controller('myCtrl', function($scope, $http){
//$scope.tok = '';
$http({
method : "POST",
url : "http://server.com/api/authenticate",
data: '{"username":"username","password":"password","rememberMe":true}',
headers:{"Content-Type": "application/json;charset=UTF-8",
}
}).then(
function mySuccess(response){
$scope.token = response.data.id_token;
}, function myError(response){
console.log(response);
});
$http({
method: "GET",
url: "http://server.com/api/account",
data: '',
headers:{"Authorization": "Bearer " + $scope.token,
"Content-Type": "application/json;charset=UTF-8"}
}).then(
function mySuccess(response){
console.log(response);
}, function myError(response){
console.log(response);
});
});
Of course that happens because your token is returning AFTER your second request.
On the fly you can solve it like this:
angular.module('myApp', []).controller('myCtrl', function($scope, $http){
//$scope.tok = '';
$http({
method : "POST",
url : "http://server.com/api/authenticate",
data: '{"username":"username","password":"password","rememberMe":true}',
headers:{"Content-Type": "application/json;charset=UTF-8",
}
}).then(
function mySuccess(response){
$scope.token = response.data.id_token;
$http({
method: "GET",
url: "http://server.com/api/account",
data: '',
headers:{"Authorization": "Bearer " + $scope.token,
"Content-Type": "application/json;charset=UTF-8"}
}).then(
function mySuccess(response){
console.log(response);
}, function myError(response){
console.log(response);
});
});
}, function myError(response){
console.log(response);
});

$q.all promises inject data from first promise to second promise

i would like to know if it's possible here with $q.all:
var promise1 = $http({
method: 'GET',
url: "https://cubber.zendesk.com/api/v2/organizations/"+id+"/users.json",
dataType: 'json',
headers: {'Content-Type': 'application/json',
'Authorization': 'Bearer '+token}
})
var promise2 = $http({
method: 'GET',
url: "https://cubber.zendesk.com/api/v2/users/"+idname+"/tickets/requested.json",
dataType: 'json',
headers: {'Content-Type': 'application/json',
'Authorization': 'Bearer '+token}
});
$q.all([promise1, promise2]).then(function(data){
console.log(data[0], data[1]);
});
If it's possible to retrieve data from promise 1 and inject into the url of promise 2 and then retrieve full data of both promises in the same array ?
For example like this
var responses = [];
$http({ ... }).then(function (response) {
responses.push(response);
return $http({ ... });
}).then(function (response) {
responses.push(response);
console.log(responses[0], responses[1]);
});
See also this answer, with many different ways to handle it.

$q.all create dynamic promises with a loop in angularjs

I want to make a loop which englobe my second promise so every time it pass in my loop a new promise is create:
var promise1 = $http({
method: 'GET',
url: "https://cubber.zendesk.com/api/v2/organizations/"+id+"/users.json",
dataType: 'json',
headers: {'Content-Type': 'application/json',
'Authorization': 'Bearer '+token}
});
var promise2 = promise1.then(function(data) {
console.log(data);
for(i = 0; i < data.data.users.length; i++){
console.log(data.data.users.length);
var userid = data.data.users[i].id;
console.log(userid);
return $http({
method: 'GET',
url: "https://cubber.zendesk.com/api/v2/users/"+userid+"/tickets/requested.json",
dataType: 'json',
headers: {'Content-Type': 'application/json',
'Authorization': 'Bearer '+token}
})
}
});
$q.all([promise1, promise2]).then(function(data){
console.log(data[0].data.users, data[1]);
});
In this code, the loop is not working because promise2 only return one result.
Can you help me pls?
Think of your code more as a chain of events that you want to fire off. Forget synchronous - forget the line by line perspective.
In this case, we fire off the first http request. Then, in respone to the request, we fire off a bunch of userid http requests, and build up an array list of the returned promises.
Then using $q.all, we respond collectivley to all those promises, and do a console log.
var promise1 = $http({
method: 'GET',
url: "https://cubber.zendesk.com/api/v2/organizations/"+id+"/users.json",
dataType: 'json',
headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer '+token}
});
promise1.then(function(data) {
var allQ = [];
var allData = [];
console.log(data);
for(i = 0; i < data.data.users.length; i++){
console.log(data.data.users.length);
var userid = data.data.users[i].id;
console.log(userid);
allQ.push( $http({
method: 'GET',
url: "https://cubber.zendesk.com/api/v2/users/"+userid+"/tickets/requested.json",
dataType: 'json',
headers: {'Content-Type': 'application/json',
'Authorization': 'Bearer '+token}
}).then( function(data){ allData.push( data)} ) );
}
$q.all(allQ).then(function(data){
//You will probably want to iterate allData
console.log( allData);
});
});

how to change post['Content-Type'] in angularjs

i want to change post['Content-Type'] in angularjs so i use
app.config(function($locationProvider,$httpProvider) {
$locationProvider.html5Mode(false);
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
});
and the event is
$http.post("http://172.22.71.107:8888/ajax/login",{admin_name:user.u_name,admin_password:user.cert})
.success(function(arg_result){
console.log(arg_result);
});
};
however the rusult is
Parametersapplication/x-www-form-urlencoded
{"admin_name":"dd"}
what i want is
Parametersapplication/x-www-form-urlencoded
admin_name dd
so what i should do?
Try like:
var serializedData = $.param({admin_name:user.u_name,admin_password:user.cert});
$http({
method: 'POST',
url: 'http://172.22.71.107:8888/ajax/login',
data: serializedData,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}}).then(function(result) {
console.log(result);
}, function(error) {
console.log(error);
});
angular.module('myApp', [])
.config(function ($httpProvider) {
$httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
})
OP is using Content-Type : application/x-www-form-urlencoded so you need to use $httpParamSerializerJQLike to change post data from JSON to string
note: there is no data property but is params property
$http({
method: 'POST',
url: 'whatever URL',
params: credentials,
paramSerializer: '$httpParamSerializerJQLike',
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
Additionally, you can inject the serializer and use it explicitly with data property
.controller(function($http, $httpParamSerializerJQLike) {
....
$http({
url: myUrl,
method: 'POST',
data: $httpParamSerializerJQLike(myData),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
Have a look at this:
How can I post data as form data instead of a request payload?
Alternatively, you could do the following:
$http.post('file.php',{
'val': val
}).success(function(data){
console.log(data);
});
PHP
$post = json_decode(file_get_contents('php://input'));
$val = print_r($post->val,true);

Resources