Following is the code I use, I get the Authentication Success Alert if the basic auth succeeds but the else alert "Authentication failed" is never displayed when the credentials are wrong. I do not use any routes and I don't have a need to use interceptors. Is there a way to get the 401 errors without using interceptors?
this.authorize = function(request, callbackFunc) {
var encodedString = btoa(request.userName + ":" + request.password);
var basicAuthString = 'Basic ' + encodedString;
var requestObject = {
location: '40005'
};
var req = {
method: this.method,
crossDomain: true,
url: this.loginURL,
data: requestObject,
headers: {
'Authorization': basicAuthString,
'Content-Type': 'application/json',
'Accept': '*/*',
'apiKey': ''
}
};
$http(req)
.success(function(response) {
callbackFunc(response, "success");
})
.error(function(response) {
console.log("Error Received");
callbackFunc(response, "error");
});
};
In Controller:
$scope.Login = function() {
AuthenticationService.authorize($scope.LoginRequest, function(response, responseCode) {
if (responseCode === "success") {
alert("Authentication Success");
} else {
alert("Authentication Failed");
}
});
};
As described in the AngularJS documentation for $http, the $http call returns a promise with an error method, which has the code(number) of the status as one of it's parameters. You can check for a 401 status in there:
error(function(data, status, headers, config) {
if(status === 401){
// Add your code here
}
});
Related
There is post request to get token for user . I have used angular $http.post method In my browser network window its not giving me response but when i try this in postman it gives me response here is screen shot attached
please help
this.login = function (loginData) {
var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password;
//if (loginData.rememberMe) {
data = data + "&client_id=" + constants.AUTHSETTINGS.CLIENT_ID;
//}
debugger;
console.log(data)
var deferred = $q.defer();
$http.post(api_url + '/token', data, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.then
(function (response) {
if (loginData.rememberMe) {
localStorageService.set('authorizationData', { token: response.data.access_token, userName: loginData.userName, refreshToken: response.data.refresh_token, useRefreshTokens: true });
}
else {
localStorageService.set('authorizationData', { token: response.data.access_token, userName: loginData.userName, refreshToken: "", useRefreshTokens: false });
}
console.log('---auth servcie')
console.log(response)
authentication.isAuth = true;
authentication.userName = loginData.userName;
authentication.useRefreshTokens = loginData.rememberMe;
deferred.resolve(response);
}
,function (err, status) {
console.log('auth error -- here ')
console.log(err)
console.log(status)
deferred.reject(err);
//deferred.resolve(err);
});
return deferred.promise;
};
raw data
var data = "grant_type=password&username=asad#gmail.com&password=1234&client_id=angularjs
my http request is not working after my token is expired in first refresh but in second refresh is work fine, but the function is executing fine what have done wrong. i work in angular frame
$http({
url: "http://localhost/ArisSystem/api/system/subsystem",
method: "GET",
dataType: 'json',
ContentType: 'application/x-www-form-urlencoded',
params: {
parentId: $scope.systemIdToLoad
},
headers: authHeaders
}).then(function (response) {
$scope.subsystem = response.data;
}), function (xhr, status, error) {
if (refreshtoken && xhr.status === 401) {
$scope.refreshlocal();
}
}
$scope.refreshlocal = function () {
$.ajax({
url: "http://localhost/ArisSystem/login",
data: {
refresh_token: refreshtoken,
grant_type: 'refresh_token'
},
type: 'POST',
dataType: 'json',
ContentType: 'application/x-www-form-urlencoded',
success: AjaxSucceeded,
error: AjaxFailed
})
function AjaxSucceeded(response) {
localStorage.setItem('accessToken', response.access_token);
localStorage.setItem('refreshToken', response.refresh_token);
refreshtoken = localStorage.getItem('refreshToken');
accesstoken = localStorage.getItem('accessToken');
authHeaders.Authorization = 'Bearer ' + accesstoken;
}
function AjaxFailed(err, response) {
window.location.href = "login.html"
}
}
You have a typo in your then function. The error-callback is outside the argument list. Instead it should be this:
$http({
...
}).then(function (response) {
$scope.subsystem = response.data;
}, function (xhr, status, error) {
if (refreshtoken && xhr.status === 401) {
$scope.refreshlocal();
}
});
I simply moved the ) from the 5th line back after the error-callback function.
That ought to do it. I'd suggest you do change the second request from $.ajax to use the $http service as well, just to keep your code consistent.
I have made a HTTP post API call to a URL.
I am getting the response, but I am confused how to write a success function, as there are many ways for it.
Here's my API call. Please help me how would the success function would be like?
var req = {
method: 'POST',
url: viewProfileurl,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + $rootScope.token,
},
params: {
'action':'view'
}
}
$http(req);
Angular uses promise internally in $http implementation i.e. $q:
A service that helps you run functions asynchronously, and use their
return values (or exceptions) when they are done processing.
So, there are two options:
1st option
You can use the .success and .error callbacks:
var req = {
method: 'POST',
url: viewProfileurl,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + $rootScope.token,
},
params: {
'action': 'view'
}
}
$http(req).success(function() {
// do on response success
}).error(function() {
});
But this .success & .error are deprecated.
Official deprecation notice
http://www.codelord.net/2015/05/25/dont-use-$https-success/
So, go for the 2nd option.
2nd Option
Use .then function instead
var req = {
method: 'POST',
url: viewProfileurl,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + $rootScope.token,
},
params: {
'action': 'view'
}
}
$http(req).then(function() {
// do on response success
}, function() {
// do on response failure
});
You need to write a success callback to retrive the data returned by your API.
$http(req)
.then(function (response) {
var data = resposne.data;
...
}, function (error) {
var errorStatusCode = error.StatusCode;
var errorStatus = error.Status;
...
});
Basically $http returns a promise and you need to write a callback function.
Or you can do something like this:
$http(req).success(function(respData) { var data = respData; ... });
$http(req).error(function(err) { ... });
This is success and error syntax
$http.get("/api/my/name")
.success(function(name) {
console.log("Your name is: " + name);
})
.error(function(response, status) {
console.log("The request failed with response " + response + " and status code " + status);
};
Using then
$http.get("/api/my/name")
.then(function(response) {
console.log("Your name is: " + response.data);
}, function(result) {
console.log("The request failed: " + result);
};
$http returns a promise that has a then function that you can use.
$http(req).then(function (data) { ...; });
The definition of then:
then(successCallback, failCallback)
This code fetches categories and give them to controller.
sampleApp.factory('SCService', function($http, $q) {
var SuperCategories = [];
var SCService = {};
SCService.GetSuperCategories = function() {
var req = {
method: 'POST',
url: SuperCategoryURL,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: "action=GET"
};
if ( SuperCategories.length == 0 ) {
return $http(req).then(function (response) {
SuperCategories = response.data;
return SuperCategories;
});
}else {
return $q.when(SuperCategories);
}
}
return SCService;
});
I think code is perfect until there is no error in http request.
My query is how to do error handling (try catch or something like that), in case if server have some issue or may be cgi-script have some issue and not able to server the request.
Angular promises use a method catch for that.
return $http(req).then(function (response) {
SuperCategories = response.data;
return SuperCategories;
}).catch(function(error) {
// Do what you want here
});
You should use also finally :
return $http(req).then(function (response) {
SuperCategories = response.data;
return SuperCategories;
}).catch(function(error) {
// Do what you want here
}).finally(function() {
// Always executed. Clean up variables, call a callback, etc...
});
Write like
return $http(req).then(function (response) {
//success callback
},
function(){
//Failure callback
});
Use callback methods from controller Like
Controller.js
service.GetSuperCategories(function (data) {console.log('success'},function (error){console.log('error'});
service.js
sampleApp.factory('SCService', function($http, $q) {
var SuperCategories = [];
var SCService = {};
SCService.GetSuperCategories = function(successMethod,errorMethod) {
var req = {
method: 'POST',
url: SuperCategoryURL,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: "action=GET"
};
return $http(req).then(successMethod(data),
errorMethod(error));
}
return SCService;
});
You can use the .success and .error methods of $http service, as below
$http(req).success(function(data, status, headers){
// success callback: Enters if status = 200
}).error(function(status, headers){
// error callback: enters otherwise
});
I've just started learning Angular.js. How do I re-write the following code in Angular.js?
var postData = "<RequestInfo> "
+ "<Event>GetPersons</Event> "
+ "</RequestInfo>";
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (req.readyState == 4 || req.readyState == "complete") {
if (req.status == 200) {
console.log(req.responseText);
}
}
};
try {
req.open('POST', 'http://samedomain.com/GetPersons', false);
req.send(postData);
}
catch (e) {
console.log(e);
}
Here's what I have so far -
function TestController($scope) {
$scope.persons = $http({
url: 'http://samedomain.com/GetPersons',
method: "POST",
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
$scope.data = data; // how do pass this to $scope.persons?
}).error(function (data, status, headers, config) {
$scope.status = status;
});
}
html
<div ng-controller="TestController">
<li ng-repeat="person in persons">{{person.name}}</li>
</div>
Am I in the right direction?
In your current function if you are assigning $scope.persons to $http which is a promise object as $http returns a promise object.
So instead of assigning scope.persons to $http you should assign $scope.persons inside the success of $http as mentioned below:
function TestController($scope, $http) {
$http({
url: 'http://samedomain.com/GetPersons',
method: "POST",
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
$scope.persons = data; // assign $scope.persons here as promise is resolved here
}).error(function (data, status, headers, config) {
$scope.status = status;
});
}
Here is a variation of the solution given by Ajay beni. Using the method then allows to chain multiple promises, since the then returns a new promise.
function TestController($scope) {
$http({
url: 'http://samedomain.com/GetPersons',
method: "POST",
data: postData,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(response) {
// success
},
function(response) { // optional
// failed
}
);
}
use $http:
AngularJS: API: $http
$http.post(url, data, [config]);
Implementation example:
$http.post('http://service.provider.com/api/endpoint', {
Description: 'Test Object',
TestType: 'PostTest'
}, {
headers {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose'
}
}
).then(function (result) {
console.log('Success');
console.log(result);
}, function(error) {
console.log('Error:');
console.log(error);
});
Lets break this down: Url is a little obvious, so we skip that...
data: This is the body content of your postman request
{
Description: 'Test Object',
TestType: 'PostTest'
}
config: This is where we can inject headers, event handlers, caching... see AngularJS: API: $http: scroll down to config Headers are the most common postman variant of http that people struggle to replicate in angularJS
{
headers {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose'
}
}
Response: the $http actions return an angular promise, I recommend using .then(successFunction, errorFunction) to process that promise see AngularJS: The Deferred API (Promises)
.then(function (result) {
console.log('Success');
console.log(result);
}, function(error) {
console.log('Error:');
console.log(error);
});