Post request is not working in angularjs - Resource services - angularjs

I'm trying to send the post request to server with post data
it's sent the request to the server, but not in right format
request url like /rest/api/modifyuser/?currentPassword=admin&newPassword=admin
it's like GET request - (may be this is problem)
I'm new to angularjs . please share idea to solve this problem
Here is my code
In controller
var currentPass = "admin";
var newPass = "admin";
var confirmPass = "admin";
var authToken = "abcdef";
User.changePassword(currentPass, newPass, confirmPass, authToken, function(response) {
angular.forEach(response, function (item) {
alert("resp"+ item);
});
});
In services
UIAppResource.factory('User', function($resource) {
return {
changePassword: function(currentPass, newPass, confirmPass, authtoken, callback) {
var Resq = $resource(baseURL + "modifyuser", {}, {
'query': {
method: 'POST',
params: {
'currentPassword': currentPass,
'newPassword': newPass,
'confirmPassword': confirmPass
},
headers: {
'Accept':'application/json',
'Content-Type':'application/json',
'X-Internal-Auth-Token': authtoken
},
isArray: false
}
});
Resq.query(callback);
}
};
});
Thanks in advance

I dont want to say you are doing it all wrong.. but you are def. abusing things. The default way to POST something with ng-resource is to use save. Second, the default way to send data is to instantiate a $resource factory with the data you want. See _resource below. We pass the data we want, and it will automagically convert it and if its a POST send it in the body, or in the case of a GET it will turn into query parameters.
UIAppResource.factory('User', function($resource) {
return {
changePassword: function(currentPass,
newPass,
confirmPass,
authtoken,
callback
) {
var Resq = $resource(baseURL + "modifyuser", {}, {
'save': {
method: 'POST',
headers: {
'Accept':'application/json',
'Content-Type':'application/json',
'X-Internal-Auth-Token': authtoken
}
}
});
var _resource = new Resq({
'currentPassword': currentPass,
'newPassword': newPass,
'confirmPassword': confirmPass
});
_resource.$save(callback);
}
};
});

Related

Angular $http.post to retrieve JWT

I am attempting to make my code more reusable, but have come across a problem when making $http calls, if I use my normal way:
vm.loginUser = function () {
var userData = {
username: vm.userName,
password: vm.userPassword,
grant_type: "password",
client_id: "E0..."
};
console.log('userData: ', userData);
var config = {
headers: {"Content-Type": "application/x-www-form-urlencoded"},
transformRequest: function (data) {
var str = [];
for (var d in data)
if (data.hasOwnProperty(d)) str.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
return str.join("&");
}
};
console.log('config: ', config);
$http.post('https://a.n.org.uk/token', userData, config)
.then(function (response) {
console.log('Button clicked: ', response);
}, function (response) {
console.log(response.data.error_description);
}, function (response) {
console.log(response.data);
});
This works fine and doesn't give me any problems. I have made a factory that is basically the same but doesn't seem to work with giving me OPTIONS error in the console and preflight check... No 'Access-Control-Allow-Origin' header'I wondered if this is a simple fix, I am using Web API.
factory("homeResource", function ($http, $q) {
return {
getUser: getUser
};
function getUser(userData) {
var request = $http({
method: "post",
url: "https://a.n.org.uk/token",
data: userData,
config: {
headers: {"Content-Type": "application/x-www-form-urlencoded"},
transformRequest: function (data) {
var str = [];
for (var d in data)
if (data.hasOwnProperty(d)) str.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
return str.join("&");
}
}
});
return (request.then(handleSuccess, handleError));
}
function handleSuccess(response) {
return ( response.data );
}
In my Ctrl page I pass in my homeResource and call it like so homeResource.getUser(userData).then(function (res) {console.log(res);}); and get the errors mentioned. Is there a way to make this work?
try the following factory method
app.factory('homeResource', function($http) {
return {
getUser: function(userData) {
var config = {
headers: {"Content-Type": "application/x-www-form-urlencoded"},
transformRequest: function (data) {
var str = [];
for (var d in data)
if (data.hasOwnProperty(d))
str.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
return str.join("&");
}
};
return $http.post('https://a.n.org.uk/token', userData, config);
}
}
});
and use it in your controller like this.
app.controller('AppCtrl',function($scope, homeResource){
vm.loginUser = function () {
var userData = {
username: vm.userName,
password: vm.userPassword,
grant_type: "password",
client_id: "E0..."
};
homeResource.getUser(userData).success(function(res){
console.log("response is",res);
})
.error(function(err) {
console.log("err is",err);
});
}
})
Your error related to cross-origin request - in other words you send request to another domain or specific route miss Access-Control-Allow-Origin server header.
Check ports, http/https and domain. Seems it's not related to your refactor.

Edit data before sending with ngResource

Hey I want to change the data before sending it with ngResource (build FormData object). I do everything as in the examples that I found, however I can't make them work. Here is my code:
My controller where I set the data and try to send them:
var vm = this;
vm.application = new Application();
vm.application.title = 'Test title';
Application.save({}, vm.application, function(){
});
My service:
function application(ApiBaseUrl, $resource) {
var actions = {
'save': {
metod: 'POST',
url: ApiBaseUrl + "/applications",
headers: { 'Content-Type': false },
transformRequest: function (data) {
console.log(data); //Returns 'undefined'
return data;
}
}
};
return $resource(ApiBaseUrl + "applications/:id", {}, actions);
}
In the function transformRequest data object is always marked as 'undefined'. Am I doing something wrong? Is there a better way to edit the data before sending it?
The problem was I had
metod: 'POST'
when I should have used:
method: 'POST'

Nodejs post request

I am trying to login to a website with the following request:
var request = require('request');
var options = {
method: 'POST',
url: 'https://server/EnterpriseController',
params: {a: 1},
form: "actionType=authenticateUser&reqObj=[null,username,password,null,1]",
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
withCredentials: true,
rejectUnauthorized: false
};
request(options,
function (error, response, body, data) {
if (request.method === 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
var post = qs.parse(body);
});
}
console.log(body);
}
);
I am always getting an error. I think the form is wrong but I have the same login on an angularjs site without any error. I don't understand why the login works on angularjs site but not in nodejs.
)]}',
{"login_err": true, "resp": [null,null,null,1]
}
I missed the cookie:/ And the Formdata should be an Object.

how to create a method in service for http post in angular?

i have
$http({
url: 'http://webapi.-----UA_WebApi/GetUserAccount',
method: 'POST',
params: {Username:Username, Password:Password},
headers: { 'Content-Type': 'application/json;charset=utf-8' },
})
and in my service i wrote this method :
PostLogin: function (apiName, params) {
var fullParams = getFullParams(apiName, params);
var promise = $resource(buildUrl(apiName), {}, POST).get(fullParams).$promise;
updateAllowedFilters(promise);
return promise;
}
if anyone could help me understand what i am doing (right and wrong) pls ?
i would also like an example in how to use the angular resource for post.
the PostLogin works
PostLogin: function (apiName, params) {
var fullParams = getFullParams(apiName, params);
var promise = $resource(buildUrl(apiName), {}, POST).get(fullParams).$promise;
updateAllowedFilters(promise);
return promise;
}
.then(function (results) {
if(results.data.TotalRows==1) {}
TotalRows is undefined when debugging. but there is TotalRows in the api
thanks
var actions = {
post: {
method: 'post',
transformResponse: function(data) {
// here is your chance to change received data
return new Model(angular.fromJson(data));
}
}
};
var url = "http://postSomeData/:id/somethingElse/:name";
var parameters = { id : 1, name : "test" }
var data = { name : "test", type : "some type" };
return $resource(url, parameters, actions).post(data).$promise;

Dynamic Resource Headers

I would like to have service providing a resource as in the following code:
angular.module('myApp.userService', ['ngResource'])
.factory('UserService', function ($resource)
{
var user = $resource('/api/user', {},
{
connect: { method: 'POST', params: {}, isArray:false }
});
return user;
}
Then when using the connect action, I would like to dynamically pass a HTTP header, meaning that it may change for each call. Here is an example, in the controller, please see the comment in the code :
$scope.user = UserService;
$scope.connect = function ( user )
{
var hash = 'Basic ' + Base64Service.encode(user.login + ':' + user.password);
// I would like this header to be computed
// and used by the user resource
// each time I call this function
$scope.user.headers = [{Authorization: hash}];
$scope.user.connect( {},
function()
{
// successful login
$location.path('/connected');
}
,function()
{
console.log('There was an error, please try again');
});
}
Do you know a way to do that, either directly or via a trick?
Final thoughts
Accepted answer does not fully answer the question as the headers are not totally dynamic because the factory returns actually a factory (!) which is not the case in my code.
As $resource is a factory, there is no way to make it dynamic.
I finally destroy the resource object each time the user connects. This way, I have the resource with a header computed when the user connects.
The solution provided by #Stewie is useful for that, so I keep it as accepted.
Here is how I did the connect, which can be used multiple times as the resource is destroyed/recreated when (re)connecting:
this.connect = function (user)
{
self.hash = 'Basic ' + Base64Service.encode(user.login + ':' + user.password);
console.log("CONNECT login:" + user.login + " - pwd:" + user.password + " - hash:" + self.hash);
if (self.userResource)
{
delete self.userResource;
}
self.userResource = $resource('/api/user/login', {}, {
connect: {
method: 'POST',
params: {},
isArray: false,
headers: { Authorization: self.hash }
}
});
var deferred = $q.defer();
self.userResource.connect(user,
function (data)
{
//console.log('--------- user logged in ----- ' + JSON.stringify(data));
// successful login
if (!!self.user)
{
angular.copy(data, self.user);
}
else
{
self.user = data;
}
self.setConnected();
storage.set('user', self);
deferred.resolve(self);
},
function (error)
{
self.user = {};
self.isLogged = false;
storage.set('user', self);
deferred.reject(error);
}
);
return deferred.promise;
};
Starting from angularjs v1.1.1 and ngResource v.1.1.1 this is possible to accomplish using the headers property of the $resource action object.
You may wrap your resource in a function which accepts custom headers as a parameter and returns a $resource object with your custom headers set at the appropriate action definitions:
PLUNKER
var app = angular.module('plunker', ['ngResource']);
app.controller('AppController',
[
'$scope',
'UserService',
function($scope, UserService) {
$scope.user = {login: 'doe#example.com', password: '123'};
$scope.connect = function() {
// dropping out base64 encoding here, for simplicity
var hash = 'Basic ' + $scope.user.login + ':' + $scope.user.password;
$scope.user.headers = [{Authorization: hash}];
UserService({Authorization: hash}).connect(
function () {
$location.url('/connected');
},
function () {
console.log('There was an error, please try again');
}
);
};
}
]
);
app.factory('UserService', function ($resource) {
return function(customHeaders){
return $resource('/api/user', {}, {
connect: {
method: 'POST',
params: {},
isArray: false,
headers: customHeaders || {}
}
});
};
});
I set my Services up a little differently.
angular.module('MyApp').factory('UserService',function($resource, localStorageService) {
var userResource = function(headers) {
return $resource("api/user", {},
{
get: {
method: 'GET',
headers: headers
},
create: {
method: 'POST',
headers: headers
}
}
);
};
return {
api: userResource,
get: function(userid){
var service = this;
return service.api({"token": "SomeToken"}).get({userid: userid}, function (data){
return data;
});
},
create: function(user){
var service = this;
return service.api({"token": localStorageService.get("token")}).create({user: user}, function (data){
return data;
});
}
};
});

Resources