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
Related
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);
});
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;
};
}])
I am using angularjs with node js as server.
I am passing data this way from UI.
schatApp.controller('registerController', function($scope,$location,$http) {
$scope.RegisterCredentials=function(){
var data={
"firstName":"simhachalamrsdafrds",
"lastName":"ajay",
"username":"asfsd",
"email":"ajayfds14#m.com",
"provider":"local",
"displayName":"amruth"
}
// var json = "{\"firstName\": \"firstName\",\"lastName\": \"lastName\",\"username\": \"username\",\"email\": \"email\"}";
var config = {
headers : {
contentType:'application/json; charset=utf-8',
dataType: 'json'
}
}
$http.post("/register",JSON.stringify(data),config).then(function sucess(result){
// alert(JSON.stringify(result));
},function failure(result){
// alert(JSON.stringify(result));
});
}
});
This is my backend code
app.post('/register',function(req,res){
var data={
firstName:'simhachalam',
lastName:'ajay',
username:'asfsdq',
email:'ajayfds14#mq.com',
provider:'local',
displayName:'amruth'
}
console.log("111...............");
//console.log(req.body);
//res.setHeader('Content-Type', 'application/json');
core.account.create('local',data,function(err){
if (err) {
var message = 'Sorry, we could not process your request';
if (err.code === 11000) {
message = 'Email has already been taken';
}
return res.status(400).json({
status: 'error',
message: message
});
}
res.status(201).json({
status: 'success',
message: 'You\'ve been registered, ' +
'please try logging in now!'
});
});
});
I am getting 400 bad request.
Its very difficult to say what could be the issue, you need to do a console.log(err) object. can you give that information for us here.
if (err) {
var message = 'Sorry, we could not process your request';
if (err.code === 11000) {
message = 'Email has already been taken';
}
return res.status(400).json({
status: 'error',
message: message
});
}
The above code clearly states that you are returning res.status(400), can you change your $http.post to below and check.
$http({
method: 'POST',
url: "/register",
data: JSON.stringify(data),
headers: {'Content-Type': 'application/json; charset=utf-8'}
});
hopefully your /register endpoint is hosted on the same server where you are serving the client from.
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.