I am trying to send a post request with both a header and request body. So far I have reached this point:
createJob: function(jobName, jobAddress, jobContact, jobComments) {
var payload = {
name: jobName,
address: jobAddress,
contact: jobContact,
comments: jobComments
};
console.log(payload);
return $resource(route, {}, {
save: {
method: 'POST',
header: {'Content-Type': 'application/json'},
transformRequest: function(data){
console.log('Data in transform request is');
console.log(data);
return data; // this will go in the body request
}
}
});
}
I am not sure where to place the payload in this case, any help? Also when making the call, I am currently trying to do something like:
createJob(this.jobName, this.jobAddress, this.jobContact, this.jobComments).
save().$promise.
then(function (response) {
console.log('Create job response is');
console.log(response);
}).
catch(function (error) {
console.log('Create job error is');
console.log(error);
});
Any help would be appreciated!
I came to a solution for anyone that is interested:
createJob: function(jobName, jobAddress, jobContact, jobComments) {
var payload = {
name: jobName,
address: jobAddress,
contact: jobContact,
comments: jobComments
};
console.log(payload);
return $resource(route, {}, {
save: {
method: 'POST',
transformRequest: function(data){
console.log('Data in transform request is');
console.log(data);
return angular.toJson(data); // this will go in the body request
}
}
}).save({}, payload);
}
createJob(this.jobName, this.jobAddress, this.jobContact, this.jobComments).$promise.
then(function (response) {
console.log('Create job response is');
console.log(response);
//Refresh the page so newly created job can be seen
window.location.reload();
}).
catch(function (error) {
console.log('Create job error is');
console.log(error);
});
Related
I can't access the output variable from my 1st http get request, i need this data for another http Post request.
None.
$scope.submit = function(x) {
$http({
method: "GET",
url: url + 'getOSchild',
params: { ncard: x }
}).then(function success(response) {
$scope.osChild = response.data;
console.log($scope.osChild) // this has an output
}, function error(response, status) {
console.log(response)
console.log(status)
});
$http({
method: "POST",
url: url + 'printOS',
data: JSON.stringify({
CARD_NAME: data_cname,
C_DATE: data_date,
C_NUMATCARD: data_ncard,
C_DISTMEANS: data_means,
C_TIME: data_time,
cData: $scope.osChild //this is null
}),
header: {
'Content-Type': 'application/json'
},
}).then(function success(response) {
console.log(response)
}, function error(response, status) {});
}
I need the $scope.osChild to be present in my http post request.
Simply chain the two XHRs:
function getOSChild (x) {
return $http({
method: "GET",
url: url+'getOSchild',
params: {ncard: x}
}).then(function success(response) {
$scope.osChild = response.data;
console.log($scope.osChild); // this has an output
return response.data;
},function error(response) {
console.log(response)
console.log(response.status);
throw response;
});
}
$scope.submit = function(x) {
getOSChild(x).then(function(osChild) {
$http({
method: "POST",
url: url+'printOS',
data:{ CARD_NAME: data_cname,
C_DATE: data_date,
C_NUMATCARD: data_ncard,
C_DISTMEANS: data_means,
C_TIME: data_time,
cData: osChild //chained
}
}).then(function success(response) {
console.log(response)
});
});
};
The .then method returns a new promise which is resolved or rejected via the return value of the successCallback, errorCallback (unless that value is a promise, in which case it is resolved with the value which is resolved in that promise using promise chaining.
For more information, see
AngularJS $q Service API Reference - chaining promises
You're Missing the Point of Promises
first GET call is asynchronous so $scope.osChild setting null initially. so suggestion is to use Promises https://ng2.codecraft.tv/es6-typescript/promises/
$scope.getOSChild = function() {
var deferred = $q.defer();
$http.get(url + 'getOSchild')
.then(function onSuccess(response) {
$scope.osChild = response.data;
deferred.resolve(response.data);
}).catch(function onError(response) {
console.log(response.data);
console.log(response.status);
deferred.reject(response.status);
});
return deferred.promise;
};
$scope.submit = function(x) {
$scope.getOSChild().then(function (osChild) {
$http({
method: "POST",
url: url + 'printOS',
data: JSON.stringify({
CARD_NAME: data_cname,
C_DATE: data_date,
C_NUMATCARD: data_ncard,
C_DISTMEANS: data_means,
C_TIME: data_time,
cData: osChild
}),
header: {
'Content-Type': 'application/json'
},
}).then(function onSuccess(response) {
console.log(response);
}, function onError(response, status) {});
});
};
I am trying to pass a variable through AJAX to an API. Here is the angular controller:
$scope.register = function() {
_.each($scope.photos, function(images) {
$upload.upload({
url: '/api/indorelawan/timaksibaik/register/upload-images',
method: 'POST',
data: {},
file: images
})
.success(function(data) {
$scope.team.photos.push(data.result.path);
})
});
$http({
method : 'POST',
url : '/api/indorelawan/timaksibaik/register',
data : $.param($scope.team),
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success(function(data) {
if (!data.success) {
...
}
else {
...
}
});
}
I tried console.log the $scope.team.photos before it calls the /register API. It displays the data perfectly. But when /register API is runned, the $scope.team.photos is not included. Here is the API:
/*Register Tim Aksi Baik*/
apiRouter.post('/timaksibaik/register', function(req, res) {
// TODO: Create new value to access general statistics data, e.g.: response time.
console.log(req.body);
var team = new GoodActionTeam();
_.each(req.body, function(v, k) {
team[k] = v;
});
team.created = new Date();
team.save(function(err, data) {
if (err) {
res.status(500).json({
success: false,
message: "Gagal menyimpan data organisasi baru.",
system_error: "Error while saving organization data: " + err.message
});
}
else {
res.status(200).json({
success: true,
message: "Organisasi Berhasil Dibuat",
result: data
});
}
});
});
The output of the req.body is only:
{ logo: '/uploads/user_avatar/register/2018-1-14_18:18:3.png',
name: 'ererr',
url_string: 'ererr',
description: 'dfdfd',
focuses: [ '549789127e6a6e2c691a1fc0', '549789127e6a6e2c691a1fc0' ] }
It looks like the $scope.team.photos is not included when the data is passed to the API. What went wrong?
The $upload.upload() is async and by the time you make a post with $scope.team there is no guarantee that all the upload success callbacks have been completed
I have recetly began an adventure with AngularJs but idea of promises and returning asynchonous data overhelmed me.
I am trying to accomplish simple data returining via .factory method and $resource service.
Here is my $resource service returning promise
(function () {
angular.module('token')
.factory('tokenService', ['$resource', 'baseUri', tokenService]);
function tokenService($resource, baseUri) {
return $resource(baseUri + 'token', {}, {
post: {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
});
}
})();
I am using this service in another service which should returns data.
(function () {
angular.module('authorization')
.factory('authorizationService', ['$httpParamSerializer', 'tokenService', authorizationService]);
function authorizationService($httpParamSerializer, tokenService) {
return {
authorization: function(user){
var token = {};
tokenService.post({}, $httpParamSerializer({
grant_type: 'password',
username: user.login,
password: user.password,
client_id: user.clientId
}), function(response){
token = response;
console.log('authorizationResponse', response);
console.log('authorizationToken', token);
});
// .$promise.then(function(response){
// token = response;
// console.log('authorizationResponse', response);
// console.log('authorizationToken', token);
// });
console.log('finalToken', token);
return token;
}
};
}
})();
But i cannot force token variable to posses tokenService.post() result before returing.
First: inject $q in your authorizationService.
Try this:
authorization: function(user) {
return $q(function(resolve, reject) {
tokenService.post({}, {
grant_type: 'password',
username: user.login,
password: user.password,
client_id: user.clientId
})
.$promise
.then(function(token) {
resolve(token);
})
.catch(function(err) {
reject(err);
});
});
}
Then, in your controller, you can use:
authorizationService.authorization(user)
.then(function(token) {
// Some code here
})
.catch(function(err) {
// Handle error here
});
I am trying to make a post request through Angular. My code looks as follows,
Javascript Code looks like:
GET:
$scope.getRecord = function() {
debugger;
$http({
method: 'GET',
url: 'SomeURL'
}).then(function(response) {
debugger;
$scope.mainEntity = response.data.anEntity;
}, function(error) {
$scope.content = "something went wrong"
});
};
Post:
$scope.save = function() {
debugger;
var body = JSON.stringify({
"xyzaa": $scope.value.xyzaa || "One fielfd of its",
"xyzbb": $scope.value.xyzbb || One fielfd of its,
"xyzcc": $scope.value.xyzcc || "One fielfd of its",
"xyzaaa": $scope.value.xyzaaa || "One fielfd of its"
});
var request = {
method: 'POST',
url: 'Some URL',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin' : '*'
},
data: body
};
$http(request).then(function (result) {
debugger;
$scope.getRecord();
}, function (error) {
debugger;
console.log(error)
alert("error")
})
};
Well, I can see that the post request returns the data that I have done in a JSON Format, yet am receiving the error:
POST http://localhost:xyz/xyz/a (Unprocessable Entity)
Object {data: Object, status: 422, config: Object, statusText: "Unprocessable Entity"}.
I can see that data that am being posting is getting in the data key and I can see the data that I have passed, yet I get this error and it doesnt change in the api
Hi I have an issue that I can't really explain with res.json from express.
Here is my /login route:
router.post('/login', function (req, res) {
if (req.body.user) {
var newUser = (typeof req.body.user === 'string') ? JSON.parse(req.body.user) : req.body.user;
User.findOne({ email: newUser.email })
.exec(function (err, user) {
if (err) {
return res.json({ error: true, data: err });
} else {
if (user !== undefined && user !== null) {
// Check password and generate a token if it exist
encrypt.checkHash(newUser.pwd, user.pwd, function (err, isCorrect) {
if (err) {
return res.json({ error: true, data: err });
} else {
if (isCorrect != false) {
// Generate token and send it
Token.generateToken({
_id: user._id, email: user.email,
iat: moment().valueOf(),
exp: moment().add(30, 'minutes').valueOf(),
},
conf.secret,
{},
function (err, token) {
if (err) {
return res.json({ error: true, authenticate: false, data: err });
} else {
console.log('Logged');
return res.json({
error: false,
token: token,
authenticate: true,
msg: 'user_connected',
});
}
});
} else {
console.log('Not logged');
return res.json({ error: true, authenticate: false, msg: 'user_undefined' });
}
}
});
} else {
return res.json({ error: true, authenticate: false, msg: 'user_undefined' });
}
}
});
} else {
return res.json({ error: true, authenticate: false, msg: 'user_empty' });
}
});
And here the function where I made my request to that route:
userRequest.auth = function (user) {
console.log('AUTH userRequest ', user);
$http({
method: 'POST',
url: url + '/auth/login',
dataType: 'application/json',
data: { user: user },
}).then(function successCallback(response) {
$log.warn('user request', response);
deferred.resolve(response);
}, function errorCallback(err) {
deferred.reject(err);
});
return deferred.promise;
};
And here my onClick function which start the process
var promise = userRequest.auth($scope.user);
promise.then(function (response) {
var data = response.data;
$log.info('Login RESPONSE ', response);
if (data.error == false && data.authenticate == true) {
$log.info('You are logged');
$scope.notification = setAlertBoxOptions($scope.notification, true, 'alert-success', 'Vous ĂȘtes maintenant connectĂ©');
} else {
$log.info('Wrong informations');
$scope.notification = setAlertBoxOptions($scope.notification, true, 'alert-danger', 'Utilisateur inconnue');
}
}, function (reason) {
$log.error(reason);
});
My function's encrypt.checkHash callback work and the value isCorrect is the good one when checking my password hash. It log 'Logged' if the password is correct and 'Not logged' if it's not.
The first time I made a request on this route it send me back an response by res.json and I get the expected data.
But after the first request, the data I receive is always the one I received on the first query.
e.g: The first time I send correct identification info and it return me
{error: false, token: token, authenticate: true, msg: 'user_connected'}
but after that, every time I try to make another query on that route I keep receiving this JSON object event if my identification info are false.
I'm not an expert in Nodejs and I tried to replace all my
res.json({...})
by
return res.json({...})
to stop the execution but the result still the same.
Can you share your wisdom with me and help me solve this case please ?
I found out why it was happening, in my angularJS factory I initialize only once the $q service and where using it inside a method of the factory. like this:
angular.module('myApp').factory(
'userRequest',
['$log', '$q',
function ($log, $q) {
// Initialized wrongly
var deferred = $q.defer();
userRequest.auth = function (user) {
console.log('AUTH userRequest ', user);
$http({
method: 'POST',
url: url + '/auth/login',
dataType: 'application/json',
data: { user: user },
}).then(function successCallback(response) {
$log.warn('user request', response);
deferred.resolve(response);
}, function errorCallback(err) {
deferred.reject(err);
});
return deferred.promise;
};
}])
instead of:
angular.module('myApp').factory(
'userRequest',
['$log', '$q',
function ($log, $q) {
userRequest.auth = function (user) {
// Where to initialize it
var deferred = $q.defer();
console.log('AUTH userRequest ', user);
$http({
method: 'POST',
url: url + '/auth/login',
dataType: 'application/json',
data: { user: user },
}).then(function successCallback(response) {
$log.warn('user request', response);
deferred.resolve(response);
}, function errorCallback(err) {
deferred.reject(err);
});
return deferred.promise;
};
}])