When the following route is called in express, it is actually executed 6 times. The console.log is printed 6 times, and my mongoose logic is executed 6 times (saves 6 time in database).
I then get returned a http 500 from cloud9ide "Could not proxy request". I am really confused, I have no loops in my code, how can this happen? The console.log("in else (2)"); get printed 6 times.
Edit: I have tried the mongooseLogic code with various parts commented out, and the issue was still there. This looks like it isn't a mongoose issue.
Second edit: I have changed the post for get and hardcoded the body that would be sent, and the route was executed only once.
Third edit: I am also using everyauth for session/authentication with the facebook oauth.
app.post("/result/:userId/:elementId", function(req, res) {
var receivedJSON = req.body;
console.log("In route");
//Making sure the receive request is valid
if(typeof(receivedJSON.type) !== undefined) {
mongooseLogic.saveResults(req.params.elementId, receivedJSON, req.params.userId, function(message) {
if(message === "Success") {
res.json({ success: true, message: 'Result saved.'});
}
else {
res.json({ success: false, message: 'Error in saving results. Trace: ' + message});
}
});
}
else {
res.json({ success: false, message: 'Failed, Invalid object sent to server'});
}
});
Code on the mongooseLogic file:
var saveResults = function(elementRefId, receivedResult, userId, callback){
if(elementRefId.toString().length !== 24 ){
callback("Invalid objectId for elementId");
}
else{
Result.findOne({ "id" : userId, "serieResult.id": elementRefId }, function(err, result){
if(err){
callback("No Document found: " + err);
}
else if( result === null){
console.log("in null");
var tempResult = {
id : elementRefId,
unit : receivedResult.unit,
value : receivedResult.value
}
Result.update({ "id" : userId}, { $push: {"serieResult": tempResult}}, {upsert: true}, function(err){
if(err){
callback("Error in saving result (Distance): " + err);
}
else{
callback("Success");
}
});
}
else{
Result.update({ "id" : userId, "serieResult.id": elementRefId },
{ $set:{
"serieResult.$.unit" : receivedResult.unit,
"serieResult.$.value" : receivedResult.value,
},{upsert: true}, function(err){
if(err){
callback("Cant update doc: " + err);
}
else{
console.log("in else (2)");
callback("Success");
}
});
}
});
}
}
}
This was a problem with the Cloud9 proxy that interfered. The problem was adressed thanks to this issue and has been resolved.
Related
I have problem how to check specific document from MongoDb in NodeJs with if operator.
My MongoDb collection looks liket this (I only need document "button"):
{
"_id" : ObjectId("5e95eb9da19c2430d4952754"),
"title" : "Krepšinis",
"author" : "5e90eb1abbcb1f33e8b17720",
"place" : "dsadas",
"count" : 10,
"going_count" : 5,
"button" : "Būsiu",
"__v" : 0
}
My NodeJs:
router.post('/:id', function(req, res){
let post = {};
if(post.button == "Būsiu"){
post.button = "Nebūsiu";
} else {
post.button = "Būsiu";
}
let query = {_id:req.params.id}
Post.update(query, post, function(err){
if(err){
console.log(err);
return;
}
req.flash('success', 'Postas Atnaujintas');
res.send('Success');
});
});
The problem is I don't get any errors, it just doesn't work.
And this is my Ajax:
$(document).ready(function(){
$('.going').on('click', function(e){
console.log('working')
$target = $(e.target);
const id = ($target.attr('data-id'));
$.ajax({
type:'POST',
url: '/posts/'+id,
success: function(response){
alert('Važiuojam');
},
error: function(err){
console.log(err);
}
});
});
});
I don't really know what to try else, because I'm pretty new to programming.
Can you try specifying the mongodb aggregation pipeline and check what the result of affected documents in the query is as below
router.post('/:id', function(req, res){
let post= {};
if(post.button == "Būsiu"){
post.button = "Nebūsiu";
} else {
post.button = "Būsiu";
}
let query = {_id:req.params.id}
Post.update(query, {$set:post}, function(err, response
){
if(err){
console.log(err);
return;
}
console.log(response.result.nModified)
req.flash('success', 'Postas Atnaujintas');
res.send('Success');
});
});
I am trying to check if a user already exists in the database, I have managed to stop creating a user if one already exists with the same phone number , however I do not seem to get the error message displayed. I am not too sure why my error is not being handled correctly. Here is my code:
exports.usercreate = function (req, res)
{
users.create(req.body, function (err, result)
{
var phonenumber = req.body.phonenumber;
console.log(phonenumber);
if (phonenumber.length > 0)
{
res.status(200).json(
{
status: "error",
resCode: 400,
msg: 'cutomer added error'
});
}
else
{
res.status(200).json(
{
status: "success",
resCode: 200,
msg: "users Added Successfully",
});
}
else
{
console.log(error)
}
});
};
Getting error like customer added error. but records are inserted in couchbase
as #TommyBs mentioned, you are basically comparing an N1qlQuery object to whatever is coming on req.body.phonenumber
...
bucket.query(query, function(err, rows, meta) {
for (row in rows) {
if(row.phonenumber == req.body.phonenumber) {
res.status(500).json({status:"error", resCode: 500, msg:"users Already exist"});
}
}
}
I am newbie with JavaScript, NodeJS and Express. I writing simple application which does the following
User makes a request.
Server makes mulitple rest calls and renders the response.
How can I make sure that all the calls are complete and I create an object that I can send to the user? I saw people said something about async.parallel. Is that the only way to go? Any examples would help.
You can use promises to run code in sequence.
Here is an example (a little scaled down) of a login functionality I made using promises.
In a module named LoginController I have placed this piece of code.
this.attemptLogin = function(body, res) {
var reason = "";
var user = null;
loginM.findUser(body.username)
.then(function(result) {
if (result.status) {
user = result.result[0];
return this.verifyPassword(body.password, result.result[0].Password);
} else {
reason = {status: false, message: "Incorrect username", result: null};
throw(reason);
}
})
.then(function(result) {
if (result.message) {
res.send({status: true, message: "Successfully logged in", result: user});
return;
} else {
reason = {status: false, message: "Incorrect password", result: null};
throw(reason);
}
}).catch(function(err) {
res.send(err);
});
}
And in another module named LoginModel (LoginM) I have placed this code
this.findUser = function(username, email) {
return new Promise(function (resolve, reject) {
pool.getConnection(function (err, connection) {
if (err) {
reject({status: false, message: err});
} else {
connection.query('select Id, Name, Email, Password from Users ' +
'where (Users.Name = ? OR Users.Email = ?) AND Removed = 0 LIMIT 1', [username, email], function (err, rows) {
connection.release();
if (!err) {
if(rows.length > 0) {
resolve({status: true, message: "Found user", result: rows});
}
else
resolve({status: false, message: null})
} else {
reject({status: false, message: err});
}
});
}
});
});
}
And a similar method for verifyPassword which also returns a promise.
Now, the things to note are that:
the code inside every then is run asynchronously
the then parts are executed in order, i.e, you won´t enter the next then until you have returned something from the previous then
whatever you resolve from the methods returning promises (findUser and verifyPassword) are passed as the variable named result in .then(function(result)
I am very new to express and node. I was trying to upload an image using multiparty and code given here.
I have put a check for file size. When I upload a file of size greater than the limit it lands in the "problem section". The problem is the server hangs and responds back only after request timeout. I have tried many solution on stack overflow but nothing seems to work. It works if the file size is below the limit. I am very sure that the code reaches the problem section and there is no problem with the upload logic. But it seems that I have to do something in the "problem section". Please tell me what am I missing.
I have replaced the code in the problem section with
next(), res.send(), res.end(), next(err), return; but It does not work. It hangs no matter what.
Following is the code:
router.post("/image", function(req, res, next) {
if(req.user) {
upload.uploadToS3(req, S3_BUCKET, S3_PROFILE_IMAGE_FOLDER, function(result) {
if(result.error != null && result.error === false) {
models.Customer.update({
orignalImage : result.fileLocation
},{
where : { mobileNumber : req.user.mobileNumber}
}).then(function(customer) {
if(customer) {
res.send({
url: result.fileLocation,
error : false
});
} else {
res.status(400);
res.send({error : true,
error_message : 'Image upload failed'});
}
});
} else {
//PROBLEM SECTION
res.status(404);
res.json({error : true, error_message : result.error_message});
}
});
} else {
res.status(403);
res.send({message: "access denied"});
}
});
response after timeout
Please tell me if you need more details I will upload it.
var uploadToS3 = function(req, S3_BUCKET, folder, callback) {
var s3Client = knox.createClient({
secure: false,
key: awsConfig.accessKeyId,
secret: awsConfig.secretAccessKey,
bucket: S3_BUCKET,
});
var headers = {
'x-amz-acl': 'public-read',
};
var form = new multiparty.Form();
var batch = new Batch();
batch.push(function(cb) {
form.on('part', function(part) {
var validity = validateFile({type : part.headers['content-type'], name : part.filename, length : part.byteCount});
console.log(validity);
if(validity.isValid) {
cb(null, { filename : folder+"/"+generateFileName({name : part.filename}), part : part});
} else {
cb({error : true, error_message : validity.reason, part:part }, "advra kedavra");
}
});
});
batch.end(function(err, results) {
if (err) {
console.log(err);
err.statusCode = 200;
callback(err);
} else {
form.removeListener('close', onEnd);
var result = results[0];
var part = result.part;
var destPath = result.filename;
var counter = new ByteCounter();
part.pipe(counter); // need this until knox upgrades to streams2
headers['Content-Length'] = part.byteCount;
s3Client.putStream(part, destPath, headers, function(err, s3Response) {
result = {};
if(err) {
console.log(err);
result.error = true;
result.error_message = "Problem in uploading!";
} else {
console.log(s3Response.req.url);
result = {error: false, statusCode : s3Response.statusCode, message : "file upload successful.", fileLocation : s3Response.req.url};
}
callback(result);
});
part.on('end', function() {
console.log("File upload complete", counter.bytes);
});
}
});
function onEnd() {
console.log("no uploaded file");
callback({error:false, error_message:"no uploaded file."});
}
form.on('error', function(err) {
console.log('Error parsing form: ' + err.stack);
});
form.on('close', onEnd);
form.parse(req);
}
After a 3 day long search for the answer I found one answer. Express.js close response
The problem section should be the following :
res.status(400);
res.set("Connection", "close");
res.json({error:true, error_message : "<some - error message>"});
You should simply add a .end() after setting the status as: res.status(400).end();
See official docs
res.end([data] [, encoding])
Ends the response process. This method actually comes from Node core, specifically the response.end() method of http.ServerResponse.
Use to quickly end the response without any data. If you need to respond with data, instead use methods such as res.send() and res.json().
res.end();
res.status(404).end();
res.status(400);
res.set("Connection", "close");
res.json({error:true, error_message : "<some - error message>"});
I am not sure that solves your issue. The 'problem section' is in your callback, which would only run after the upLoadToS3 function runs. The 'problem' is probably with that function. You might have to refactor that to handle large file uploads.
I am trying to POST a request for /draft and create a new "draft" / update an existing one in my database. after that I want to instantly redirect to the /draft?id=RELEVANT_ID_HERE page.
this is my current POST request function:
app.post('/draft', function(req,res){
var id = req.query.id;
var postTitle = req.body.head;
var article = req.body.article;
if(id){
db.postCatalog.findOneAndUpdate({_id: id}, {title:postTitle, inShort:article.substring(0,100), content:article}, function(err, data){
if (err) {
return handleError(err);
}
else {
console.log(data);
res.status(200).redirect('/draft?id='+id);
}
});
}
else{
id = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
new db.postCatalog({title:postTitle,
_id:id,
author:'temp',
AuthorID:2,
date:'2/3/12',
inShort:article.substring(0,100),
content:article ,
published:false
}).save(function (err, data) {
if (err) {
return handleError(err);
}
else {
console.log(data);
res.status(200).redirect('/draft?id='+id);
}
});
}
});
so, everything works except for the redirect. I am getting the correct GET request in the node console, but nothing happens in the browser.
this is the code for the GET request:
app.get('/draft', function(req,res){
var id = req.query.id;
if(id){
db.postCatalog.findOne({_id: id}, function(err, post){
if(err) {
return handleError(err);
}
else{
if(post){
console.log(post);
res.status(200).render('editDraft.hbs', {post: post});
}
else{
routes._404(req,res);
}
}
});
}
else{
console.log('creating new draft');
res.status(200).render('editDraft.hbs');
}
});
I am using Express and Mongoose. view engine is Handlebars.
Thanks for reading!
I think the status 200 is throwing you off. Try using a 302 and it should work.
res.writeHead(302, {
'Location': '/draft?id='+id
});
res.end();