HttpResponseMessage from WebAPI from angular http post call - angularjs

I have a UI project , which is an Angular JS project and Web API project and i am new to Angular. I am calling a login method of API controller which does the DB check and its sending OK message. But its going to error part of Angular http promise call. What can be the possible reasons? This is the API Call
function AutenticateUser(input) {
var deferred = $q.defer();
$http({
method: 'POST',
data: input,
url: config.serviceUrl + config.loginUrl,
transformRequest: function (input) {
var str = [];
for (var p in input)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(input[p]));
return str.join("&");
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json'
}
}).then(function (result) {
userInfo = {
accessToken: result.data.access_token,
userName: input.username
};
}, function (error) {
deferred.reject(error);
});
return deferred.promise;
}
Does the accept header has to do anything with it?

Related

write angular js service to access multiple function

I am using below function to loadbenefittypes.
my get data function
$scope.loadCashBenefitTypes = function (){
$http({
method: "GET",
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.getItem('JWT_TOKEN')
},
url: appConfig.apiUrl + "/benefit-types/income?income_type=Cash Benefit",
}).then(function (response) {
$scope.func1 = response.data
}, function (response) {
});
}
i am using above function to load benefit types in multiple locations in my application. therefore i need to reuse this function as a service. how i convert above function and how i assign it to different drop down models
To re-factor the code to a service, return the $http promise:
app.service("myService", function($http, appConfig) {
this.getCashBenefitTypes = function (){
return $http({
method: "GET",
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + localStorage.getItem('JWT_TOKEN')
},
params: { income_type: 'Cash Benefit' },
url: appConfig.apiUrl + "/benefit-types/income",
}).then(function (response) {
return response.data;
});
}
});
Then inject that service in the controllers:
app.controller("app", function($scope, myService) {
myService.getCashBenefitTypes()
.then(function(data) {
$scope.types = data;
}).catch(response) {
console.log("ERROR", response);
});
});
For more information, see
AngularJS Developer Guide - Creating Services

AngularJS: Http header

I am newbie of angularJS. I want to add header in my http request but i am not understanding how? so far i've written this code.
Original code without header:
function saveUser(user, $http) {
var token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjYxLCJpc3MiOiJodHRwOlwvXC8zNC4yMDQuMjIyLjExM1wvYXBpXC91c2VycyIsImlhdCI6MTQ5NTE4MDY3MCwiZXhwIjoxNDk1MTg0MjcwLCJuYmYiOjE0OTUxODA2NzAsImp0aSI6IkdkNXdUSmZQMDRhcjc2UWIifQ.dKGZTysAibFbtruvSI7GwFV61kh43CX22g8-sRV9roQ";
var url = __apiRoot + "/users/" + user.id;
var dataObj = {
payload: JSON.stringify(user),
_method: "PUT",
}
return $http.post(url, dataObj);
}
Now i am adding header to it, the code becomes like this:
function saveUser(user, $http) {
var token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjYxLCJpc3MiOiJodHRwOlwvXC8zNC4yMDQuMjIyLjExM1wvYXBpXC91c2VycyIsImlhdCI6MTQ5NTE4MDY3MCwiZXhwIjoxNDk1MTg0MjcwLCJuYmYiOjE0OTUxODA2NzAsImp0aSI6IkdkNXdUSmZQMDRhcjc2UWIifQ.dKGZTysAibFbtruvSI7GwFV61kh43CX22g8-sRV9roQ";
var url = __apiRoot + "/users/" + user.id;
var dataObj = {
payload: JSON.stringify(user),
_method: "PUT",
}
return $http({headers: {
'Authorization': token
}}).post(url, dataObj);
}
By adding header, i am getting this error:
angular.js:14525 Error: [$http:badreq] Http request configuration url
must be a string or a $sce trusted object. Received: undefined
You're using the wrong syntax. Take a look at the angular documentation for $http here.
Your code should look like this:
$http({
method: 'POST',
url: __apiRoot + "/users/" + user.id,
data: JSON.stringify(user)
headers: {
'Authorization': token
}
}).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.
});

AngularJS success function of promise

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)

angularjs post request to nodejs api

I've angularjs post call (submit a login form data) to a /login nodejs API endpoint. The data received at Nodejs endpoint (in request.body) is not in json format but it has extra padding as shown below,
{ '{"email": "a#b.com", "password": "aaa"}': ''}
What is this format? How do I access 'email' and/or password from this object?
Client code,
login: function(loginData, callback) {
$http({
method: 'POST',
url: '/api/login',
data: loginData,
headers: {'Content-Type': 'application/x-www.form-urlencoded'}
}).then(function successCallback(response) {
}, function errorCallback(response) {
});
}
Server code:
app.post('/login', function(req, res) {
console.log('Email:' + req.body.email); //this gives undefined error
console.log(req.body); // shows { '{"email": "a#b.com", "password": "aaa"}': ''}
}
What am I missing? Any help is appreciated.
--Atarangp
By default angularjs use JSON.stringify. If you wanna use x-www-form-urlencoded, you have to specify your transform function.
// transforme obj = {attr1: val1} to "attr1=" + encodeURIComponent(val1) + "&attr2=" ...
function transformRequestToUrlEncoded(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
$http({
method: 'POST',
url: your_url,
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
transformRequest: transformRequestToUrlEncoded, // specify the transforme function
data: datas
});

Sending POST request with form-urlencoded parameters in AngularJS using ngResource

I am trying to do a POST request with ngResources in AngularJS, I want to send my parameters in url and I have changed headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, in $save method in ngResources. The request goes out with the correct content type, but the data goes as a JSON. Is there any standard way to overcome this problem?
The factory
.factory('Token', ['$resource', function ($resource) {
return $resource('http://myProject/token/ ', { }, {
save: {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}
});
}])
The calling function
.service('tokenService', ['$http', 'Token',
function ($http, Token) {
this.getToken = function () {
var t = new Token()
t.name = 'myName';
t.password = '78457'
return t.$save();
};
}])

Resources